简体   繁体   中英

React useState hook - update state of a object

I have a checklist object state

const [checkList, setCheckList] = useState({checkA, checkB .. 100 checks})

How to update all states to e.target.checked at once? I should be able to update like this:

const handleAllCheck = (e) => {
Object.keys(checkList).map((resource) => {
  setCheckList({ ...checkList, [resource]: e.target.checked });
});

};

But this updates only one of 100 checks, What am I missing?

Issues

You are enqueueing a bunch of state updates in a loop but not using a functional state update, so the same state from the current render cycle the updates are enqueued in is used for each update, overwriting the previous update. The last enqueued update wins and is the state set for the next render cycle.

const handleAllCheck = (e) => {
  Object.keys(checkList).map((resource) => {
    setCheckList({
      ...checkList, // <-- state from the previous render cycle
      [resource]: e.target.checked,
    });
  });
};

Solution

In order to update all the checked values you can simply forEach over the keys and use a functional state update to spread in the state from the previous enqueued update.

const handleAllCheck = (e) => {
  const { checked } = e.target;
  Object.keys(checkList).forEach((resource) => {
    setCheckList(checkList => ({
      ...checkList, // <-- state from the previous update
      [resource]: checked,
    }));
  });
};

Alternatively you can use a single update by reducing the old state into a new state object.

const handleAllCheck = (e) => {
  const { checked } = e.target;
  setCheckList(checkList => Object.keys(checkList).reduce(
    (checkList, resource) => ({
      ...checkList,
      [resource]: checked,
    }),
    {},
  ));
};

can you try

const handleAllCheck = (e) => {
const newCheckList = Object.keys(checkList).map((resource) => {
  return e.target.checked;
});
setCheckList(newCheckList);

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