构造函数vs componentWillMount;构造函数不能做什么组件WillMount? [英] constructor vs componentWillMount; what a componentWillMount can do that a constructor cannot?

查看:1498
本文介绍了构造函数vs componentWillMount;构造函数不能做什么组件WillMount?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所见,唯一的一个 componentWillMount 可以做,而构造函数不能调用 setState

  componentWillMount(){
setState({ isLoaded:false});
}

由于我们没有调用 render 然而, componentWillMount 中的 setState 将在进入第一个 render() pass。这是一个基本上相同的事情,一个构造函数做:

 构造函数){
super(props);
this.state = {isLoaded:false};
}






但是我看到另一个用法



让我们考虑一些异步的事情:

  componentWillMount(){
myAsyncMethod(params,(result)=> {
this.setState({data:result} );
})
}

这里我们不能使用构造函数作为赋值给 this.state 不会触发 render()



componentWillMount 中的 setState 根据反应文档


在安装之前立即调用componentWillMount()。它
render()之前调用,因此此方法中的设置状态将
不会触发重新呈现。避免在此方法中引入任何副作用或
订阅。


所以,在这里我认为React会使用新的状态值为第一个渲染并避免重新渲染。



问题1:这是否意味着在 componentWillMount ,如果我们在异步方法的回调(可以是promise回调)中调用 setState ,则React 阻止初始呈现直到回调执行?



客户端上设置此设置(是的,我在服务器端渲染中看到用例),如果我假设以上是正确的,在异步方法完成之前,我看不到任何东西。



我没有任何概念?



问题2:是否只有 componentWillMount 可以实现的任何其他用例,但不使用构造函数 componentDidMount

解决如果我们在
async方法的回调(可以是promise回调)中调用setState,那么这意味着在componentWillMount中,React块
初始化渲染直到回调执行?


否,请参阅 这里



以下代码不阻止渲染(请记住,这将作为一个反模式,无论如何调用setState在那里)

  componentWillMount:function(){
new Promise((resolve,拒绝)=> {
setTimeout(()=> {
resolve();
},2000)
})然后(()=> this.setState({promiseResult: 'world'}));
},




问题2:是否有其他用途我可以使用
componentWillMount实现的情况,但不使用构造函数和
componentDidMount?


不,对于ES6类,您可以放弃componentWillMount 。只需使用 React.createClass({...})



编辑:显然,我错了感谢@ Swapnil ,指出这一点。以下是讨论



如果构造函数中存在副作用,则会在另一个组件中修改状态,因为它假定 setState 构造函数中的code>可能在 render()期间被调用。因此,在构造函数中不需要任何副作用。



如果您在 componentWillMount ,不会抛出任何错误。另一方面,来自Facebook的人也不鼓励在 componentWillMount 中的副作用。所以如果你没有任何效果,你可以使用构造函数而不是 componentWillMount 。对于副作用,建议使用 componentDidMount 而不是 componentWillMount
无论如何,您不需要 componentWillMount


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

componentWillMount() {
    setState({ isLoaded: false });
}

Since we have not called render yet, a setState in componentWillMount will prepare the state object before we enter the first render() pass. Which is essentially the same thing a constructor does:

constructor(props) {
    super(props);
    this.state = { isLoaded: false };
}


But I see another use case where componentWillMount is useful (on server side).

Let's consider something asynchronous:

componentWillMount() {
    myAsyncMethod(params, (result) => {
        this.setState({ data: result });
    })
}

Here we cannot use the constructor as assignment to this.state won't trigger render().

What about setState in componentWillMount? According to React docs:

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.

So, here I think React will use the new state value for the first render and avoids a re-render.

Question 1: 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?

Having this setup on client-side (yes I see that use case in server-side rendering), if I assume the above is true, I will not see anything until my asynchronous method completes.

Am I missing any concepts?

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

解决方案

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 side any 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.

这篇关于构造函数vs componentWillMount;构造函数不能做什么组件WillMount?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆