gpt4 book ai didi

javascript - ReactJS onClick 状态改变落后一步

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:56:27 27 4
gpt4 key购买 nike

我正在使用 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>
)
}
}

最佳答案

setState()not necessarily a synchronous operation :

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state aft

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

由于这个原因,this.state.questionNumber 可能仍保留以前的值:

this.props.changeHeader("Question " + this.state.questionNumber)

相反,使用 callback function状态转换完成后调用:

this.setState({
questionNumber: this.state.questionNumber + 1
}, () => {
this.props.changeHeader("Question " + this.state.questionNumber)
})

关于javascript - ReactJS onClick 状态改变落后一步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41043419/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com