简体   繁体   中英

React.js - How to change object value inside array of objects

i have a problem with array of objects which is inside state. My question is how to change an object value like in example code bellow

const [theArrayOfObjects, setTheArrayOfObjects] = useState([
    { color: "blue", shape: "square" }, 
    { color: "red", shape: "circle" }
    ]);

what i want is

[
    { color: "blue", shape: "square" }, 
    { color: "red", shape: "rectangle" }
]

so in short i just want to update array of objects by changing only this specific value

setTheArrayOfObjects([
    { color: "blue", shape: "square" }, 
    { color: "red", shape: "rectangle" }
  ]
)

While this might not be exactly what you asked it fits your needs and it is simple. Further complications like iterating through each element and finding pattern to reach specific element might end up with unexpected outputs.

If you don't like this, then you might come up with different state structure (an object instead of an array).

Use a functional state update to correctly update from any previous state value. Shallow copy any parts of state that you are updating. Remember that the useState state updater function doesn't shallow merge your updates, you are returning an entire new state value.

Given:

const [theArrayOfObjects, setTheArrayOfObjects] = useState([
  { color: "blue", shape: "square" }, 
  { color: "red", shape: "circle" }
]);

Update as follows:

  • Map the previous array to a new array reference
  • Shallow copy the array element you want to update, appending the updated properties

Example:

const updateShape = (shape, index) => {
  setTheArrayOfObjects(state => state.map((el, i) => i === index
    ? { ...el, shape }
    : el,
   ));
};

...

updateShape("rectangle", 1);

Helpful

Even though it's from Redux, the Immutable Update Patterns documentation is incredibly helpful in explaining in more detail what I described above and is still applicable to standard React state updates. Please do a read though.

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