无法从数组中删除对象

时间:2017-09-29 11:20:55

标签: reactjs

我是新的反应,现在我有一个问题。我不知道如何从数组中删除一个对象。每篇文章都有一个删除按钮。如果我按下删除按钮和我的console.log,它会显示正确的对象。

当我使用splice时,它会随机删除,经过2次点击后,我的整个数组都会被清空。我需要用什么来删除正确的对象,如console.log给我看的那样?

将对象插入另一个组件并进行渲染。

这是我的代码:

class Article extends React.Component {
  constructor(props){
    super(props);   
    this.state = {
       deleteArray: this.props.entireArray
    };
     this.onClickHandler = this.onClickHandler.bind(this); 
}

   onClickDelete = () => {
   /* this.setState({
    deleteArray: this.props.articles.splice(this.props.key, 1)
  }); */ 
  console.log("delete", this.props.articles)
} 

   getArray = () => {
          this.props.sendData(this.state.deleteArray);
  } 


    onClickHandler = (e) => {
      e.preventDefault();
      this.onClickDelete();
       this.getArray();
    }

   render() {

      return (
        <div className="articleContainer">
          <div className="articleTitle"> <Link to={
            {
              pathname: "/" + this.props.articles.url + ':' + this.props.articles.id,
              state: {singleTitle: this.props.articles.title,
                      singleDate: this.props.articles.date,
                      singleText: this.props.articles.text
              }
            }
            }>{this.props.articles.title}</Link></div>
            <button onClick={this. onClickHandler} type="submit">Delete</button>
          <div className="articleDate"><FontAwesome name="clock-o"/> {this.props.articles.date}</div>
          <TextTruncate
            className="articleTruncate"
            line={1}
            truncateText="…"
            text={this.props.articles.text}

          />

        </div>
      );
    }
  } 

1 个答案:

答案 0 :(得分:0)

这是因为splice返回一个新数组,其中只包含已删除的项目。因此,当您设置新状态时,您只将已删除的项目指定为deleteArray属性的新状态。

如果你想保留原始数组并只删除一个项目,

let articles = this.props.articles;
this.props.articles.splice(this.props.key, 1);
this.setState({
   deleteArray: articles
});
相关问题