ReactJS onClick状态改变了一步 [英] ReactJS onClick state change one step behind
问题描述
我正在使用ReactJS构建一个非常原始的测验应用程序,但我无法更新 Questions
组件的状态。它的行为是它将问题
数组的正确索引呈现给DOM,尽管 this.state.questionNumber
总是一个后退在 handleContinue()
:
I'm building a very primitive quiz app with ReactJS and I'm having trouble updating the state of my Questions
component. Its behavior is it renders the correct index of the questions
array to the DOM despite this.state.questionNumber
always being one step behind in handleContinue()
:
import React from "react"
export default class Questions extends React.Component {
constructor() {
super()
this.state = {
questionNumber: 1
}
}
//when Continue button is clicked
handleContinue() {
if (this.state.questionNumber > 3) {
this.props.unMount()
} else {
this.setState({
questionNumber: this.state.questionNumber + 1
})
this.props.changeHeader("Question " + this.state.questionNumber)
}
}
render() {
const questions = ["blargh?", "blah blah blah?", "how many dogs?"]
return (
<div class="container-fluid text-center">
<h1>{questions[this.state.questionNumber - 1]}</h1>
<button type="button" class="btn btn-primary" onClick={this.handleContinue.bind(this)}>Continue</button>
</div>
)
}
}
推荐答案
setState()
是不一定是同步操作:
setState()
不会立即改变this.state
,但会创建挂起状态转换。访问this.state
aft
setState()
does not immediately mutatethis.state
but creates a pending state transition. Accessingthis.state
aft
无法保证对 setState的调用同步操作
并且可以批量调用以获得性能提升。
There is no guarantee of synchronous operation of calls to setState
and calls may be batched for performance gains.
因此,这个.state.questionNumber
可能仍然保留此前的值:
For this reason, this.state.questionNumber
may still hold the previous value here:
this.props.changeHeader("Question " + this.state.questionNumber)
,使用一旦调用的回调函数状态转换已完成:
Instead, use the callback function that is called once the state transition is complete:
this.setState({
questionNumber: this.state.questionNumber + 1
}, () => {
this.props.changeHeader("Question " + this.state.questionNumber)
})
这篇关于ReactJS onClick状态改变了一步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!