javascript - 渲染后如何根据另一个状态使用 setState 更新状态?
问题描述
我正在尝试在渲染 jsx 后根据其他状态更新状态。
有些状态已更新,但有些未更新。
请考虑检查“ComponentDidMount()”。我不确定发生了什么事!
为什么他们没有得到相应的更新?
我很困惑!
import React, { Component } from "react";
export class MathQuiz extends Component {
constructor(props) {
super(props);
this.state = {
num1: 0,
num2: 0,
op_type: "",
op: "",
result: 0,
no_right: 0,
no_wrong: 0,
options: <li />,
ans_pos: 0,
options_and_pos: [[], 0]
};
}
componentDidMount() {
this.genNums();
this.initQuiz(this.props.location.state.op_type);
}
initQuiz(op_type) {
this.setState({ op_type: op_type });
if (op_type === "Addition") {
this.setState({ op: "+" });
this.setState(prevState => ({ result: prevState.num1 + prevState.num2 }));
} /* Code */
} else if (op_type === "Multiplication") {
this.setState({ op: "x" });
this.setState(prevState => ({ result: prevState.num1 * prevState.num2 }));
console.log(this.state.result);
this.setState({ options_and_pos: this.getOptions(this.state.result) });
this.setState({
options: this.state.options_and_pos[0].map((ele, i) => (
<li key={i}>{ele}</li>
))
});
this.setState({ ans_pos: this.state.options_and_pos[1] });
}
genNums() {
this.setState({
num1: this.genRandRange(1, 100),
num2: this.genRandRange(1, 100)
});
}
getOptions(ans) {
/* Code */
return [ans_options, rand_pos];
}
render() {
return (
<div className="math_quiz_box">
/* JSX Code */
</div>
);
}
}
解决方案
React 文档可以帮助你:
setState() 并不总是立即更新组件。它可能会批量更新或将更新推迟到以后。这使得在调用 setState() 之后立即读取 this.state 是一个潜在的陷阱。
并为您提供解决方案:
相反,使用 componentDidUpdate 或 setState 回调 (setState(updater, callback)),它们都保证在应用更新后触发。
因此,请确保在更新状态后不要立即使用状态。
推荐阅读
- laravel - 在 Laravel 5.6 中一次插入父母和孩子
- c# - ASP .NET 4.7 MVC 身份验证和授权标识
- python - 根据每个值的关联值从字典创建映射
- java - Spring Batch-MySQL 问题
- visual-studio-code - Visual Studio Code 切换在网格视图中打开文件
- java - 如何在 Kibana 之外的 AWS 托管的 Elasticsearch 中查询 + 重新索引
- java - 在任务中更新消息会挂起应用程序
- python - 程序无法在编辑器(sublime、atom)上运行并因在 Web 编辑器上使用 13 CPU 秒而关闭
- javascript - javascript中的基类
- angular - *ngFor 项目选择错误 - Angular