setState没有合并值 [英] setState is not merging the values
本文介绍了setState没有合并值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在响应中使用以下代码来更新状态。 州
最终应如下所示:
I use the following code in react in order to update state. state
should finally looks like this:
this.state.output = {
'abc':{
value: 10
},
'cde':{
value: 20
}
// new values are added and old kept (if not overwritten)
}
我的处理程序:
handleChange = (data) => {
this.setState(prevState => {
return {
output: {
[data.id]: { ...data },
},
}
})
}
数据传递时使用新的data.id到 handleChage
,输出
不添加新密钥,而是完全替换其所有内容
When the data is passed in to handleChage
with a new data.id, output
does not add the new key, instead completely replace all its content
this.state.output = {
'new':{
value: 2
},
}
我还需要保留上一个密钥。我的代码有什么问题?
I need instead keep the previous key also. What is wrong in my code?
推荐答案
因为你忘了添加其他属性及其值,所以更新对象如下:
Because you forgot to add the other property and their values, update the object like this:
handleChange = (data) => {
this.setState(prevState => {
return {
output: {
...prevState.output, // notice this
[data.id]: { ...data },
},
}
})
}
或简单地说:
handleChange = (data) => {
this.setState(prevState => ({
output: {
...prevState.output,
[data.id]: { ...data },
},
})
)}
这篇关于setState没有合并值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文