繁体   English   中英

方法中没有 state 更新

[英]no state update in the method

我的 state 未更新。console.log (newQuestion) - 显示例如 3 个元素,在 qBank 中仍有 10 个元素

gameIp= (id) => {
    const newQuestion2 = [];
    for (const point of this.state.qBank) {
        if (id === point.RouteId) {
            newQuestion2.push({
                question: point.Question1,
                answers: [...point.Answers],
                correct: point.Correct,
                id: point.Id,
            });

        }
    }
    this.setState({ qBank: newQuestion2 });
}

this.setStateasync行为,因此如果您按顺序运行以下代码:

this.setState({ qBank: newQuestion2 });

console.log(this.state.qBank); // Will not show you updated state

如果要检查更新的 state,可以使用setState callback

this.setState({ qBank: newQuestion2 } , () => {
    console.log(this.state.qBank); // <--- Here you can check updated state
});

因此,您可能会感到困惑的是您的 state 没有更新,但是一旦 state 更新,这些更改就会反映在 UI 中,因为它会强制 dom 重新渲染。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM