javascript - 如何强制 setState 执行更改?
问题描述
我正在尝试部分更改组件的状态,但不幸的是它并没有像我预期的那样执行。
我以这种方式初始化状态:
constructor(props){
super(props);
this.state = {
array: [],
status: false,
interval: null,
animations: [],
algorithm: null
}
}
我尝试使用它的方式
if(this.state.status === false){
this.change_style(text);
//The change
this.setState({status: true, animations: [], algorithm: "Bubble_Sort"});
const arr = this.state.array.slice();
this.bubble_sort_and_push(this.state.animations, arr);
this.animate(this.state.animations);
}
经过一些研究,我发现setState
只有在上一个状态与新状态之间存在实际变化时才会改变状态(在我的情况下它确实有差异)
所以我无法真正理解为什么这些变化没有通过。
我尝试只更改其中一个字段
if(this.state.status === false){
this.change_style(text);
console.log(this.state.status);
//The change
this.setState({status: true})
console.log(this.state.status);
const arr = this.state.array.slice();
this.bubble_sort_and_push(this.state.animations, arr);
this.animate(this.state.animations);
}
通话之间没有区别console.log
,但确实发生了变化。
我怎样才能setState
在我调用它的那一刻进行表演?
我已经尝试使用forceUpdate()
并阅读它与 的连接DidComponentUpdate
,但无法真正弄清楚如何将它们连接起来以像我期望的那样工作。
解决方案
setState是异步的,你永远不应该假设更改会立即发生:
https://reactjs.org/docs/react-component.html#setstate
React 在后台执行一些操作,例如将状态更改捆绑在一起以提高效率(批量更新内容)。
在功能组件中,解决方案是使用useEffect钩子,具有非空依赖项数组。当依赖数组中的变量发生变化时,React 会触发useEffect :
useEffect(() => {
// code performed when stateVariable has changed
}, [stateVariable]);
在基于类的组件中,解决方案将暗示componentDidUpdate生命周期方法:
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.state.stateVariable !== prevState.stateVariable) {
// code performed when stateVariable has changed
}
}
推荐阅读
- .net - 如何调用托管在 IIS 上的 POST API 方法
- spring - 使用弹簧安全性在后端启用 CORS 的正确方法是什么。在 REST 框架的项目中也使用 Apache cxf
- java - 编写一个循环,直到您在控制台中输入内容
- c# - c#如何检查选择了哪一行列表框
- powershell - 长powershell命令的自动屏幕捕获(不是文本输出)
- java - 在我的Java程序中,为什么我绑定到0.0.0.0时会涉及IP6?
- python - 根据另一列对一列进行分箱并交叉制表
- sql-server - 如何在 SERVER 上安装 SSIS/SSDT 自定义任务
- c++ - 如何编写带有“自动”字推导类型的参数的函数?
- jquery - 将jquery变成R中的可用字符串