简体   繁体   中英

Trying to update an array in an object inside of an object. React, useState

I have an onChange method that looks like this:

const onChangeEnableWhenValueCalculation = i => (event) =>{
      setItem({
        ...newItem,
        enableWhen: [
          {
           linkId: newItem.enableWhen[i]?.linkId,
           operator: newItem.enableWhen[i]?.operator,
           valueCalculation: event.target.value,
          }
        ],
      });
  }

I want to change valueCalculation with event.target.value but at the specified index inside of the enableWhen.

How to I set the value of this key at specific index inside an object, inside and array, inside another object? Any help is appreciated.

If I understand correctly, I would do:

let enableWhen = [...newItem.enableWhen];
// replace the element at index i with the updated item
enableWhen.splice(i, 1, {
       linkId: newItem.enableWhen[i]?.linkId,
       operator: newItem.enableWhen[i]?.operator,
       valueCalculation: event.target.value,
});

setItem({
    ...newItem,
    enableWhen
});

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