首页 > 解决方案 > 如何强制 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,但无法真正弄清楚如何将它们连接起来以像我期望的那样工作。

标签: javascriptreactjsreact-hooks

解决方案


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
  }
}

推荐阅读