【问题标题】:Strange behaviour when removing item from state array从状态数组中删除项目时的奇怪行为
【发布时间】:2018-11-25 18:09:39
【问题描述】:

我有一个状态数组,其中包含各种组件。当我单击其中一个组件上的删除按钮时,它会从数组中删除第一项。我似乎只有在使用数组中的组件时才会遇到这个问题,它适用于字符串数组。

父组件:

addItem = (block) => {
  const add = [...this.state.items, block];
  this.setState({items: add})
}

removeItem = (index) => {
  const remove = [...this.state.items];
  remove.splice(index, 1);
  this.setState({items: remove})
}

render(){
  return(
    <div className="Board">
      <div className="BoardContainer">
        {this.state.items.map((item, index) => { return <Item remove= {this.removeItem} key={index} >{item}</Item>})}
      </div>
      <button onClick={() => this.addItem(<BannerImage />)}>Banner Image</button>
      <button onClick={() => this.addItem(<ShortTextCentered />)}>Short Text Centered</button>
    </div>
  )
}

子组件:

export class Item extends React.Component {

  handleRemove = () => {
    this.props.remove(this.props.index)
  }

  render() {
    return (
      <div className="item">
        {this.props.children}
        <button onClick={this.handleRemove} >Remove</button>
      </div>
    )
  }
}

【问题讨论】:

    标签: javascript arrays reactjs


    【解决方案1】:

    您在组件中使用了“this.props.index”,但没有将索引传递给组件。

    你应该这样做:

    {this.state.items.map((item, index) => { return <Item remove={this.removeItem} key={index} index={index} >{item}</Item>})}
    

    【讨论】:

      【解决方案2】:

      Array.prototype.splice() 会改变数组,所以最好不要在 React 中使用 splice()。

      最容易使用 Array.prototype.filter() 创建一个新数组。

      此外,使用唯一 ID 而不是索引可防止出现意外结果。

      let filteredArray = this.state.item.filter(x=> x!== e.target.value)
      this.setState({item: filteredArray});
      

      【讨论】:

        猜你喜欢
        • 2018-01-16
        • 1970-01-01
        • 2014-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-19
        相关资源
        最近更新 更多