Splice() 方法不起作用

Splice() method not works

我的 React.js 应用程序中的 splice() 方法有一些问题。

所以,this is an example app。删除现在不起作用。这里出了什么问题?部分代码:

class CardList extends React.Component {
  static propTypes = {
    students: React.PropTypes.array.isRequired
  };
  // ADD DELETE FUNCTION
  deletePerson(person) {
    this.props.students.splice(this.props.students.indexOf(person), 1)
    this.setState()
  }
  render() {
    let that = this
    return <div id='list'>
      {this.props.students.map((person) => {
        return <Card
          onClick={that.deletePerson.bind(null, person)}
          name={person.name}>
        </Card>
      })}
    </div>
  }
}

class Card extends React.Component {
  render() {
    return <div className='card'>
       <p>{this.props.name}</p>
      {/* ADD DELETE BUTTON */}
      <button onClick={this.props.onClick}>Delete</button>
    </div>
  }
}

http://codepen.io/azat-io/pen/Vaxyjv

你的问题是当你调用

onClick={that.deletePerson.bind(null, person)} 

您将 this 值绑定到 null。所以在你的 deletePerson 函数中 thisnull 而不是实际的组件。您应该将其更改为

onClick={that.deletePerson.bind(this, person)}

一切都会按预期工作=)

将绑定值更改为 this 肯定会导致对 this.setState() 的调用起作用,从而触发重新渲染,但是我强烈建议不要采用您采用的方法。

道具应该是不可变的。而是使用内部状态并用新值替换而不是改变它们。为此,请通过执行以下操作在构造函数中设置组件的状态:

constructor(props) {
    super(props)
    this.state = {
        students: ...this.props.students
    }
}

现在当你需要删除一个人时:

deletePerson(person) {
    // notice the use of slice vs splice
    var newStudents = this.props.students.slice(this.props.students.indexOf(person), 1)
    this.setState({ students: newStudents })
}

最后在渲染方法中使用 this.state.students

这背后的原因是 props 是直接从父容器组件传递的,因此修改它们实际上没有意义。为了让我自己的代码更有意义,我倾向于传入名为 initialStudents 的 prop 并将我的状态设置为 students: ...initialStudents 以确保我区分我的 prop 变量和我的状态变量。