简体   繁体   中英

ReactJS, Hooks - How to setState after .map() function?

I'm trying to change state, with values from array. Example:

const [state, setState] = useState({});
const test = [1, 2, 3];
        test.map((item, i) => {
          setState({ ...state, [`item-${i}`]: item });
        });

Current state is:

item-2: 3

What I want to achieve is:

item-0: 1,
item-1: 2,
item-2: 3

I've tried to do it in several ways (all looking similar), but the effect is the same :/ does anyone knows how to resolve it?

Thanks!

You can update the state using forEach() method like:

test.forEach((item, i) => {
   setState(state => ({...state, [`item-${i}`]: item}));
});

You can use the functional version of set state and a reduce to accomplish this:

  setState(prevState => {
    return test.reduce((acc, next, i) => {
      return {
        ...acc,
        [`item-${i}`]: next
      },
    }, prevState);
  });

This has the advantage of doing it in a single call and is easier to read.

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