小编use*_*765的帖子

在render方法中调用React中的setState()

我试图使用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`.
Run Code Online (Sandbox Code Playgroud)

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

我的代码如下:

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

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

我调用resetMsg的代码(resetMessages的值最初为false,我需要重置React-state,当它为true时):

    render() {
    if(this.props.resetMessages){           
        this.resetMsg();           
    }
Run Code Online (Sandbox Code Playgroud)

reactjs redux

6
推荐指数
2
解决办法
1万
查看次数

标签 统计

reactjs ×1

redux ×1