ReactJS:使用spread元素更新状态

时间:2017-10-13 16:39:00

标签: javascript reactjs

我收到语法错误,不确定理解原因:

当前状态如下所示:

people: [{
    id: 1,
    firstName: 'Eric',
    lastName: 'Andrews',
}, {
    id: 2,
    firstName: 'Rick',
    lastName: 'Handsome',
}, {
    id: 3,
    firstName: 'Yoni',
    lastName: 'Andrews',
}],

addNewFriend() {
    this.setState({
        people: {
            [...this.state.people, {
                id: this.state.idIncrementor + 1,
                firstName: this.state.newPerson['newFirstName'],
                lastName: this.state.newPerson['newLastName'],
            }]
        },
        newPerson: ''
    })
}


Syntax error: Unexpected token (156:26)

  154 |         this.setState(
  155 |             {
> 156 |                 people: {[...this.state.people, 
      |                           ^
  157 |                     {
  158 |                         id: this.state.idIncrementor +1, 
  159 |                         firstName: this.state.newPerson['newFirstName'],

我想合并this.state.people和新词典。 people是当前的词典列表,我想添加一个新词典。

我做错了什么?

1 个答案:

答案 0 :(得分:4)

你错过了people是一个数组,而不是一个对象,所以

people: {[...this.state.people,

应该是

people: [...this.state.people,