据我所知,一个唯一componentWillMount可以做的事和一个constructor不能做的事就是打电话给setState。
componentWillMount
constructor
setState
componentWillMount() { setState({ isLoaded: false }); }
由于我们尚未调用render,因此setStatein componentWillMount会在进入render()第一遍之前准备状态对象。本质上是相同的constructor:
render
render()
constructor(props) { super(props); this.state = { isLoaded: false }; }
但是我看到了另一个componentWillMount有用的用例(在服务器端)。
让我们考虑一些异步的东西:
componentWillMount() { myAsyncMethod(params, (result) => { this.setState({ data: result }); }) }
在这里,我们不能使用constructoras分配来this.state不会触发render()。
this.state
怎么样setState的componentWillMount?根据React docs:
componentWillMount()在挂载发生之前立即调用。在之前调用render(),因此在此方法中设置状态不会触发重新渲染。避免在此方法中引入任何副作用或订阅。
componentWillMount()
render(
因此,在这里,我认为React将在第一次渲染时使用新的状态值,并避免重新渲染。
问题1: 在内部componentWillMount,这是否意味着如果我们调用setState异步方法的回调(可以是promise回调),React会 阻止初始渲染, 直到执行该回调?
在 客户端进行 此设置(是的,我在服务器端渲染中看到了该用例),如果我假设上述情况是正确的,那么在我的异步方法完成之前,我将看不到任何东西。
我是否缺少任何概念?
问题2: 我componentWillMount仅使用而不使用constructorand 可以实现的其他用例componentDidMount吗?
componentDidMount
这是否意味着在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({... })
React.createClass({... })
编辑:显然,我错了。感谢@Swapnil指出这一点。这里是讨论。
反应引发警告,如果有在副作用constructor中的另一组件,其修饰状态,因为它假设setState在constructor本身和潜在期间render()被调用。因此,不需要任何副作用constructor。
如果在中执行此操作,则不是这种情况componentWillMount,不会引发任何错误。另一方面,来自Facebook的家伙componentWillMount也阻止了副作用。因此,如果您没有任何副作用,可以使用constructor代替componentWillMount。对于副作用,建议使用componentDidMount代替componentWillMount。无论哪种方式,您都不需要componentWillMount。