我有以下反应代码
constructor(props) {
super(props);
this.state = {registrations: [{firstName: "foo", lastName: "bar", activity: "Science Lab", restrictions: "a,b,c"}]}
}
addRegistration(registration) {
console.log('came inside event handler to add registration')
console.log(registration)
console.log('existing state')
console.dir(this.state.registrations)
var newState = this.state.registrations.splice() // copy
console.dir(newState)
newState.push(registration)
console.log(newState)
this.setState({registrations: newState})
}
当我运行我的代码并调用addRegistration事件处理程序时,我看到以下输出
[Log] {firstName: "Foo", lastName: "Bar", activity: "Swimming", restrictions: "a,b"} (Registration.html, line 404)
[Log] existing state (Registration.html, line 405)
[Log] [Object] (1) (Registration.html, line 406)
[Log] [] (0) (Registration.html, line 408)
[Log] [Object] (1) (Registration.html, line 410)
所以我得到一个有效的注册对象作为输入参数。在日志的第3个条目中,我们看到现有状态有一个大小为1的数组。(这是构造函数中的foo对象
接下来我们看到对this.state.registrations.splice()
的调用已创建且为空数组。然后将作为参数接收的新注册对象推入创建的空,从而创建另一个大小为1的数组。
我不明白为什么splice()创建了一个空数组。它应该给我一个现有状态的副本,然后推送应该导致数组大小为2.
我错过了什么?