constructor vs componentWillMount; what a componentWillMount can do that a constructor cannot?

前端 未结 1 756
小鲜肉
小鲜肉 2020-12-05 00:07

As far as I could see, the only thing a componentWillMount can do and a constructor cannot is to call setState.

compon         


        
相关标签:
1条回答
  • 2020-12-05 00:22

    Does this means, inside componentWillMount, if we call setState in an async method's callback (can be a promise callback), React blocks initial rendering until the callback is executed?

    No, see here.

    The following code doesn't block render (bear in mind this would be an anti pattern anyways to call setState there)

    componentWillMount: function() {
         new Promise((resolve, reject) => {
            setTimeout(()=> {
                resolve();
            }, 2000)
         }).then(() => this.setState({ promiseResult: 'World' }));
      },
    

    Question 2: Are the any other use cases that I can achieve with componentWillMount only, but not using the constructor and componentDidMount?

    No, for ES6 classes you can discard componentWillMount. It is only needed if you use React.createClass({... })

    EDIT: Apparently, I'm wrong. Thanks to @Swapnil for pointing this out. Here is the discussion.

    React throws a warning if there is a side effect in the constructor which modifies state in another component, because it assumes that setState in the constructor itself and potentially during render() is being called. So no side effects in the constructor are desired.

    This is not the case if you do it in componentWillMount, no errors are thrown. On the other hand, the guys from facebook discourage side effects in componentWillMount also. So if you don't have any side effects, you could use the constructor instead of componentWillMount. For side effects it is recommended to use componentDidMount instead of componentWillMount. Either way, you don't need componentWillMount.

    0 讨论(0)
提交回复
热议问题