简体   繁体   中英

Set multiple states in setState - React.js ES6

How would I add the name const to the second setState method? In order to increment currentCompany I must include the prevState. When I attempt to add the name const it does not work.

const name = company.word;

this.setState({ name });

this.setState(prevState => ({
  currentCompany: (prevState.currentCompany + 1)
}));

Thank you for your help :)

this.setState(prevState => ({
  name: company.word,
  currentCompany: (prevState.currentCompany + 1)
}));

You can write it like this also:

this.setState({ 
    name ,
    currentCompany: this.state.currentCompany + 1
})

Multiple setState within a function is not a good idea, try to do all the calculation then use setState once after that.

Function onchange set multiple state onChange(field, value){

const next = {

 ...this.state,

[field]: value

 }
this.setState(next)

 }

on HTML use onChange=e)=>this.onChange('title',e.target.value)}

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