简体   繁体   中英

How do I use 'update' & setState(prevState) together in React?

Right now I'm updating an inner object within my React Component which requires update from React. Here is my code:

const nameState = update(this.state, { userData: {name: {$set: e.target.value} }});
this.setState(nameState);

Now, the problem is that React's setState doesn't immediate make these changes but creates like a pending state change. So, the workaround this problem was using prevState . Something like this:

const enteredName = e.target.value;
  this.setState((prevState) => ({
   name : enteredName
  }));

So, how do I use prevState using my update function?

Similar to how you updated this.state :

const enteredName = e.target.value;
this.setState(prevState => update(prevState, { userData: {name: {$set: enteredName} }}));

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