Calling setState() in React from render method

前端 未结 2 2130
时光取名叫无心
时光取名叫无心 2020-12-17 23:36

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

 Warning: setState(..         


        
2条回答
  •  醉酒成梦
    2020-12-17 23:57

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

提交回复
热议问题