这是否意味着在componentWillMount内部,如果我们在异步方法的回调(可以是promise回调)中调用setState,React会阻止初始渲染,直到执行该回调?
不,请看 这里。
以下代码不会阻止渲染(请记住,无论如何在那里调用setState都是一种反模式)
componentWillMount: function() { new Promise((resolve, reject) => { setTimeout(()=> { resolve(); }, 2000) }).then(() => this.setState({ promiseResult: 'World' })); },问题2:我是否可以仅使用componentWillMount来实现其他用例,而不使用构造函数和componentDidMount来实现?
不,对于ES6类,您可以丢弃componentWillMount 。仅当您使用时才需要
React.createClass({... })编辑:显然,我错了。感谢@Swapnil指出这一点。这里是讨论。
反应引发警告,如果有在副作用
constructor中的另一组件,其修饰状态,因为它假设
setState在
constructor本身和潜在期间
render()被调用。因此,不需要任何副作用
constructor。
如果在中执行此操作,则不是这种情况
componentWillMount,不会引发任何错误。另一方面,来自Facebook的家伙
componentWillMount也阻止了副作用。因此,如果您没有任何副作用,可以使用
constructor代替
componentWillMount。对于副作用,建议使用
componentDidMount代替
componentWillMount。无论哪种方式,您都不需要
componentWillMount。



