我正在使用 ReactJS 构建一个非常原始的测验应用程序,但无法更新Questions
组件的状态。它的行为是将questions
数组的正确索引呈现给 DOM 尽管this.state.questionNumber
总是落后于DOM一步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>
)
}
}