Jac*_*art 3 javascript state reactjs
我正在使用ReactJS构建一个非常原始的测验应用程序,我无法更新Questions组件的状态.它的行为是它questions向DOM 呈现数组的正确索引,尽管this.state.questionNumber总是落后一步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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*imo 12
setState()是不必是同步操作:
setState()不会立即变异this.state但会创建待定状态转换.进入this.state船尾无法保证呼叫的同步操作,
setState并且可以对呼叫进行批处理以获得性能提升.
出于这个原因,this.state.questionNumber这里可能仍然保留以前的值:
this.props.changeHeader("Question " + this.state.questionNumber)
Run Code Online (Sandbox Code Playgroud)
相反,使用状态转换完成后调用的回调函数:
this.setState({
questionNumber: this.state.questionNumber + 1
}, () => {
this.props.changeHeader("Question " + this.state.questionNumber)
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5294 次 |
| 最近记录: |