简体   繁体   English

如何在 React Hooks 中的 state object 中设置 object 密钥

[英]How to set an object key inside a state object in React Hooks

How can I update a react hooks state object that has a nested object containing objects with index keys?如何更新反应挂钩 state object 具有嵌套的 object 包含具有索引键的对象?

Here is the default state object.这是默认的 state object。

  const [form, setForm] = useState({
      name:'',
      price:'',
      effects:{
          0:{},
          1:{},
      }

  })

My goal is to update the first key in the effects object.我的目标是更新效果object 中的第一个键。
I have tried some code like this.我试过一些这样的代码。

const variable = "Sleepy"
const variableObject = {[variable]:0} 
setForm({...form, ...{...form.effects, ...{0:{ variableObject }} }  })

This attempt places the object outside of the nested effects object like this.这种尝试将 object 置于嵌套效果object 之外,就像这样。

{
  0:{"Sleepy":0},
  1:{},
  name:'',
  price:'',
  effects:{
    0:{},
    1:{},
  } 
}

Instead, the final object state should look like this.相反,最终的 object state 应该是这样的。

{
  name:'',
  price:'',
  effects:{
    0:{"Sleepy":0},
    1:{},
  } 
}

How about:怎么样:

form.effects[0].Sleepy = 0;
setForm({...form});

The solution you are looking for is something like this,您正在寻找的解决方案是这样的,

            ...form,
            effects:{
                ...form.effects,
                0: {...variableObject}
            }
        })

the spread operator inverts the packing of the object to open it inside out.扩展运算符反转 object 的包装,将其从里向外打开。 So opening a layer, we could access the key-value pairs directly.所以打开一个层,我们可以直接访问键值对。 . . Also, there is yet another approach that might help you in the long run.此外,从长远来看,还有另一种方法可能会对您有所帮助。

    setForm((oldForm)=>{ 
        return oldForm.effects.0 = variableObject 
    })

Notice you can also use the shorthand notation to reduce the amount of code you can write.请注意,您还可以使用速记符号来减少可以编写的代码量。 Here i included the return clause to clarify the working of setState with callback.在这里,我包含了 return 子句,以阐明 setState 与回调的工作方式。 Anyways, here is the shorthand notation.无论如何,这里是速记符号。 setForm((oldForm)=> oldForm.effects.0 = variableObject) . setForm((oldForm)=> oldForm.effects.0 = variableObject) Have a nice day祝你今天过得愉快

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

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