简体   繁体   English

如何在反应 state 中更新嵌套对象数组中的数组?

[英]How to update the array in nested array of objects in react state?

I want to update age array我想更新年龄数组

  const [varient, setVarient] = useState([
    { id: 0, targets: { ageGender: { age: [], gender: [] }, parameterData } },
  ]);

After updating更新后

Result结果

Array = [
    { id: 0, targets: { ageGender: { age: [12,13], gender: [] }, parameterData } },
  ]

You could do something like this:你可以这样做:

 const addAge = (age: number) => {
    const newVarient = [...varient];
    newVarient[0].targets.ageGender.age.push(age);
    setVarient(newVarient);
  }

If you want to update your state and the new value is computed based on the previous 'snapshot' (eg value) of your state, then you can pass a function to setState.如果您想更新您的 state 并且新值是根据您的 state 的先前“快照”(例如值)计算的,那么您可以将 ZC1C425268E68385D1AB5074C17A94F 传递给 setStateF。 This function takes in the previous snapshot and returns an updated value.此 function 获取上一个快照并返回更新的值。 This is the recommended approach by the React team.这是 React 团队推荐的方法。 Read more about this concept in the documentation under subheading 'Functional updates'.在“功能更新”子标题下的文档中阅读有关此概念的更多信息。

I have added a working codesandbox example to answer your question.我添加了一个工作代码框示例来回答您的问题。

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

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