据我所知,componentWillMount
唯一可以做而 constructor
不能做的就是调用 setState
。
componentWillMount() {
setState({ isLoaded: false });
}
由于我们还没有调用render
,componentWillMount
中的setState
将在我们进入第一个render 之前准备状态对象()
通过。这与 constructor
所做的本质上是一样的:
constructor(props) {
super(props);
this.state = { isLoaded: false };
}
但我看到另一个用例,其中 componentWillMount
很有用(在服务器端)。
让我们考虑一些异步的东西:
componentWillMount() {
myAsyncMethod(params, (result) => {
this.setState({ data: result });
})
}
这里我们不能使用 constructor
因为赋值给 this.state
不会触发 render()
。
componentWillMount
中的setState
呢?根据React docs :
componentWillMount()
is invoked immediately before mounting occurs. It is called beforerender(
), therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.
因此,在这里我认为 React 将在第一次渲染时使用新的状态值并避免重新渲染。
问题 1: 这是否意味着,在 componentWillMount
中,如果我们在异步方法的回调中调用 setState
(可以是 promise 回调) , React 阻塞初始渲染直到执行回调?
在客户端 进行此设置(是的,我在服务器端渲染中看到了该用例),如果我假设上述情况属实,则在我的异步方法完成之前我将看不到任何内容。
我是否遗漏了任何概念?
问题 2: 我可以仅使用 componentWillMount
而不是使用 constructor
和 来实现的任何其他用例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?
不,见 here .
以下代码不会阻止渲染(请记住,无论如何调用 setState 都是一种反模式)
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?
不,对于 ES6 类,您可以丢弃 componentWillMount。仅当您使用 React.createClass({... })
编辑:显然,我错了。感谢@Swapnil指出这一点。这是 discussion .
如果 constructor
中存在修改另一个组件状态的副作用,React 会抛出警告,因为它假设 constructor
中的 setState
code> 本身以及可能在调用 render()
期间。因此,构造函数
中不需要任何副作用。
如果你在 componentWillMount
中这样做,情况就不是这样了,不会抛出任何错误。另一方面,来自 facebook 的人也不鼓励 componentWillMount
中的副作用。因此,如果您没有任何副作用,则可以使用 constructor
而不是 componentWillMount
。对于副作用,建议使用 componentDidMount
而不是 componentWillMount
。
无论哪种方式,您都不需要 componentWillMount
。
关于javascript - 构造函数 vs componentWillMount;什么是 componentWillMount 可以做而构造函数不能做的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40828004/