Calling setState() in React from render method

2019-02-27 09:42发布

问题:

I am trying to reset React state variables (to default values) in a container using setState() method. But getting the following error

 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`.

And finally: Maximum call stack size exceeded.

My code below:

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

I am calling resetMsg() when variable in Redux state is true.

Code where I call resetMsg (The value of resetMessages is false initially and I need to reset React-state, when its true ):

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

回答1:

You might want to look into componentWillReceiveProps(nextProps) function. As per the official docs:

componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

This is where you want to do the resets. So something like:

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

The snippet above will run every time props are sent down to the component. It first checks if the resetMessages prop is truthy. If it is, it will create a temporary copy of the company state, change the id and messages property values, and then update company with the new one.


I want to highlight the issues you had with your code:

  1. Calling setState() inside render() is a no-no.

    Whenever you call setState() in general the render() will be run afterwards. Doing so inside render() itself will cause that function to be called again, and again, and again...

  2. Mutating the state and/or props directly.

    This line const company = this.state.company; does not create a copy of the state variable. It only store the reference to it. So once you do this, and then do company.id = ... you are essentially doing this.state.company.id = ..., which is anti-pattern in React. We only ever change state through setState().

    To create a copy, use Object.assign({}, this.state.yourObject) for objects and this.state.yourArray.slice() for arrays.



回答2:

componentWillReceiveProps is deprecated now (since June'18)

You should use one of the alternatives presented in the react docs instead.

In your case I guess it could be justified to use the 'not so recommended' alternative 1 version that uses getDerivedStateFromProps, as you are just recomputing the state vars:

getDerivedStateFromProps(props, state) {
  if(props.resetMessages) {
    const company = Object.assign({}, state.company);
    company.id = 0;
    company.messages = [];    
    return {
      company: company
   }
}


回答3:

Use componentWillReceiveProps to check the props

export class SomeClass {
  resetMsg = () => {  
    let newCompany = {} // don't reuse state.company, create new object!
    newCompany = 0;
    newCompany.messages = [];    
    this.setState({company: newCompany});       
  }

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.resetMessages !== this.props.resetMessages) { // check if props changed
      if (nextProps.resetMessages === true) { // check if prop has correct value
        this.resetMsg()
      }
    }
  }

  render () {
    return () // Your super cool app code
  }
}


标签: reactjs redux