2017-10-13 90 views
0

我得到一个语法错误,不知道我理解为什么: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是当前的字典列表,我想添加一个新的字典。

我在做什么错?

+0

'{[]}'就是无效的JavaScript。你不能在这样的对象字面值中放置一个对象字面值。它与传播元素无关。 –

回答

4

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

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

应该

people: [...this.state.people, 
+0

谢谢。在11分钟内可以标记为正确。 –