简体   繁体   中英

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. This function takes in the previous snapshot and returns an updated value. This is the recommended approach by the React team. Read more about this concept in the documentation under subheading 'Functional updates'.

I have added a working codesandbox example to answer your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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