在setState中设置多个状态-React.js ES6

Tho*_*rmo 3 javascript ecmascript-6 reactjs

如何将名称const添加到第二个setState方法中?为了增加currentCompany我必须包括prevState。当我尝试添加名称const时,它不起作用。

const name = company.word;

this.setState({ name });

this.setState(prevState => ({
  currentCompany: (prevState.currentCompany + 1)
}));
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助 :)

Tho*_*rmo 6

this.setState(prevState => ({
  name: company.word,
  currentCompany: (prevState.currentCompany + 1)
}));
Run Code Online (Sandbox Code Playgroud)


May*_*kla 3

你也可以这样写:

this.setState({ 
    name ,
    currentCompany: this.state.currentCompany + 1
})
Run Code Online (Sandbox Code Playgroud)

一个函数内的多个setState不是一个好主意,尝试完成所有计算,然后setState再使用一次。