在React中,我试图让按钮增加一个存储在状态中的值。 但是,使用下面的代码函数时,我的值设置为undefined或NaN时使用handleClick。使用React将状态值增加1
class QuestionList extends React.Component {
constructor(props) {
super(props);
this.state = {value: 0};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick = (prevState) => {
this.setState({value: prevState.value + 1});
console.log(this.state.value)
}
你能告诉我为什么会发生这种情况吗?它应该是正确的根据文档在这里: https://facebook.github.io/react/docs/state-and-lifecycle.html
谢谢,我需要不使用prevState 。 – dwigt
@dwigt它你注意到我改变了你的控制台日志,在你的setstate函数的回调中。因为在setstate函数调用之后线程命中它时,内联控制台日志将会执行,而不是完成状态更新:) –