2017-08-20 74 views
0

在陣營JS組件我有這樣的代碼Reactjs setstate這通過現場

this.state.author[field] = value; 

在控制檯中我得到了一個警告:不要直接變異狀態。使用setState()

我該如何將set []中的作者放在setState中?

+1

可能重複:https://stackoverflow.com/questions/ 43040721/react-set-state-in-for-nested-state –

+0

我的問題是關於方括號中的字段選擇器[] – amorenew

回答

1

如果是把握關鍵的變量,你可以這樣做:

this.setState({author: {...this.state.author, [field]: value}}) 
1
** 

陣營使用的setState函數來更新組件的狀態,你可以做出頭像下面

**

let newAuthor = [...this.state.author]; 
newAuthor[field] = value; 
this.setState({author:newAuthor}); 
+0

很好的解決方法謝謝 – amorenew