简体   繁体   中英

Callback for setState in React inside map()

I am stuck. Hear me out:

if an array lets say arr=[{id:100,names:["abc","xyz"]}, {id:101,name:["def","pqr"]}] inside props; now my requirement is something like this:

onSave = () => {
  this.state.arr.map(obj => {
    this.setState({ [obj.id]: obj.names }}
  });
  this.accessNumIds();
}

The problem is when accessNumIds() is executing by that time the state is yet not updated. and I can't put this function in callback() of setState as i want this function to called only once.

Any Ideas?

You can do the mapping first:

const state = this.props.arr.reduce((acc, e) => { 
  acc[e.id] = e.names;
  return acc;
}, {});
this.setState(state, () => this.accessNumIds()); 

You are setting state multiples times depending on the size of props. I recommend doing setState() once with the desired data (not inside map()). If you want to execute accessNumIds() after re-rendering do it in componentDidUpdate().

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