简体   繁体   English

我正在尝试使用 useState 在反应钩子中更新 object 内的 object

[英]I'm trying to update object inside object in react hooks with useState

I'm trying to update object inside object in react hooks with useState .我正在尝试使用 useState 更新 object 内部的useState

When I create it's ok, but when I try to update only the count it's deleting the neighbors .当我创建它的时候没问题,但是当我尝试只更新count时它正在删除neighbors

This is the console after create这是创建后的控制台

{fish1: {…}} fish1: count: 1 neighbors: Array(1) 0: Array(3) 0: "fish3" 1: "fish6" 2: "fish7"

after the update更新后

{fish1: {…}} fish1: count: 2

This is the code that create or update这是创建或更新的代码

if (fishProfile.name in fishDictionary) {
  setFishDictionary({
    ...fishDictionary,
    [fishProfile.name]: {
      count: fishDictionary[fishProfile.name].count+1
    }
  })
} else {
  setFishDictionary({
    ...fishDictionary,
    [fishProfile.name]: {
      count: 1,
      neighbors: [fishProfile.Neighbors]
    }
  })
}
 if(fishProfile.name in fishDictionary){
            setFishDictionary({...fishDictionary,[fishProfile.name]:{count:fishDictionary[fishProfile.name].count+1,neighbors:fishDictionary[fishProfile.name].neighbors } })
         }
        else
        {
        setFishDictionary({...fishDictionary,[fishProfile.name]:{count:1,neighbors:[fishProfile.Neighbors]}})
        }

You are mutating state and removing properties when updating the fishDictionary state.在更新fishDictionary state 时,您正在改变 state 并删除属性。 When updating React state it is necessary to shallow copy all state, and nested state, that is being updated.更新 React state 时,有必要浅复制所有 state 和嵌套的 state,这是正在更新的。

setFishDictionary(fishDictionary => {
  if (fishProfile.name in fishDictionary) {
    return {
      ...fishDictionary,
      [fishProfile.name]: {
        ...fishDictionary[fishProfile.name], // <-- shallow copy
        count: fishDictionary[fishProfile.name].count + 1
      }
    };
  } else {
    return {
      ...fishDictionary,
      [fishProfile.name]: {
        count: 1,
        neighbors: [fishProfile.Neighbors]
      },
    };
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM