小编典典

从渲染方法在React中调用setState()

reactjs

我正在尝试使用setState()方法将容器中的React状态变量重置为默认值。但是出现以下错误

 Warning: setState(...): Cannot update during an existing state transition 
(such as within `render` or another component's constructor). Render methods 
 should be a pure function of props and state; constructor side-effects are an anti-pattern, 
 but can be moved to `componentWillMount`.

最后:超出最大调用堆栈大小。

我的代码如下:

resetMsg=()=>  {  
const company = this.state.company;
company.id = 0;
company.messages = [];    
this.setState({company: company});       
}

当Redux状态的变量为true时,我正在调用resetMsg()。

我在其中调用resetMsg的代码(resetMessages的值最初为false,当它为true时,我需要重置React状态):

    render() {
    if(this.props.resetMessages){           
        this.resetMsg();           
    }

阅读 873

收藏
2020-07-22

共1个答案

小编典典

您可能要研究componentWillReceiveProps(nextProps)功能。根据官方文档:

componentWillReceiveProps()在已安装的组件接收新道具之前调用。如果您需要更新状态以响应道具更改(例如,将其重置),则可以比较this.props和nextProps并在此方法中使用this.setState()执行状态转换。

这是您要进行重置的地方。所以像这样:

componentWillReceiveProps(nextProps) {
  if(nextProps.resetMessages) {
    const company = Object.assign({}, this.state.company);
    company.id = 0;
    company.messages = [];    
    this.setState({company: company});
  }
}

每次将道具发送到组件时,以上代码段都会运行。它首先检查resetMessages道具是否真实。如果是,它将创建状态的临时副本company,更改idmessages属性值,然后company使用新的更新。


我想强调一下您的代码遇到的问题:

  1. 调用setState()里面render()是一个没有没有。

setState()一般情况下,只要您致电,此电话render()便会在以后运行。在render()自身内部执行此操作将导致该函数一次又一次地被调用…

  1. 直接改变状态和/或道具。

该行const company = this.state.company;不会创建状态变量的副本。它仅存储对其的 引用
。因此,一旦您执行了此操作,然后company.id = ...您实际上在执行this.state.company.id = ...,这就是React中的反模式。我们只会通过改变状态setState()

要创建副本,请将其Object.assign({}, this.state.yourObject)用于对象和this.state.yourArray.slice()数组。

2020-07-22