据我所见,唯一componentWillMount可以做的constructor就是打电话setState.
componentWillMount() {
setState({ isLoaded: false });
}
Run Code Online (Sandbox Code Playgroud)
由于我们尚未调用render,因此setState在componentWillMount进入render()第一遍之前,in 将准备状态对象.这与a基本相同constructor:
constructor(props) {
super(props);
this.state = { isLoaded: false };
}
Run Code Online (Sandbox Code Playgroud)
但我看到另一个componentWillMount有用的用例(在服务器端).
让我们考虑异步的东西:
componentWillMount() {
myAsyncMethod(params, (result) => {
this.setState({ data: result });
})
}
Run Code Online (Sandbox Code Playgroud)
这里我们不能使用constructoras赋值来this.state触发render().
怎么样setState的componentWillMount?根据React文档:
componentWillMount()在安装发生之前立即调用.之前调用它render(,因此在此方法中设置状态不会触发重新渲染.避免在此方法中引入任何副作用或订阅.
所以,在这里我认为React将使用新的状态值进行第一次渲染并避免重新渲染.
问题1:这是否意味着,componentWillMount如果我们调用setState异步方法的回调(可以是一个promise回调),React会阻止初始渲染,直到执行回调为止?
在 …
我通读了https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change.我仍然无法理解为什么他们必须弃用componentWillReceiveProps.
在componentWillReceiveProps中进行ajax调用有什么危害?一旦ajax调用返回值,我就更新状态,从而重新渲染组件.