React Hooks中使用useState更新嵌套对象丢失属性问题求助
React useState更新嵌套对象丢失属性的解决办法
你遇到的问题是因为更新嵌套对象时,没有保留原对象的其他属性。当你更新fishDictionary里的某个fish对象时,只声明了count属性,这会完全替换掉原来的fish对象,导致neighbors被删除。
修改更新逻辑,在更新时展开原fish对象的所有属性,再覆盖count值即可:
if (fishProfile.name in fishDictionary) { setFishDictionary({ ...fishDictionary, [fishProfile.name]: { // 展开原对象的所有属性,保留neighbors ...fishDictionary[fishProfile.name], count: fishDictionary[fishProfile.name].count + 1 } }) } else { setFishDictionary({ ...fishDictionary, [fishProfile.name]: { count: 1, neighbors: [fishProfile.Neighbors] } }) }
这样更新后,neighbors属性会被保留,仅修改count的值。
内容的提问来源于stack exchange,提问作者tomer
相关产品推荐
相关产品推荐

