简体   繁体   中英

In React Hook, how can I change specific value of useState array?

  let [_value, setValue] = useState([1, 2, 3, 4, 5, 1, 2, 3, 4, 5 ]);

In this code, if I want to change the _value[3] how can I change value using setValue?

In my project, I have to change the _value[index] when the (rating) button is clicked.

So I have to dynamically change the _value[index].

If you know the answer, please let me know. Thank you!

In React you need to return a new state array reference. You can achieve this by mapping the previous state to the next state, using the index to match by, when the index matches return the new value, otherwise return the current value.

const updateByIndex = (newValue, index) => {
  setValue(values => values.map((value, i) => i === index ? newValue: value);
};

There are generally a couple ways to update arrays in JavaScript. Importantly, whatever you do, you want to make sure you don't mutate the existing state.

One way is to make a shallow copy of the array, mutate the copy, and set the new state:

function update(index, newValue) {
  // shallow copy
  const newArray = [..._value];
  // mutate copy
  newArray[index] = newValue;
  // set state
  setValue(newArray);
}

Another option is to map over the array, returning the new value when the index matches the desired index.

function update(index, newValue) {
  const newArray = _value.map((v, i) => {
    if (i === index) return newValue;
    return v;
  });
  setValue(newArray);
}

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