2017-10-13 76 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分鐘內可以標記爲正確。 –