据我所知,componentWillMount
能做而constructor
不能做的唯一一件事就是拨打setState
.
componentWillMount() {
setState({ isLoaded: false });
}
由于我们还没有调用render
,componentWillMount
中的setState
将在我们进入第一个render()
过程之前准备state对象.这与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()
.信息技术
因此,我认为React将在第一次渲染时使用新的状态值,并避免重新渲染.
Question 1:这是否意味着,在componentWillMount
内部,如果我们在异步方法的回调(可以是promise 回调)中调用setState
,则在执行回调之前对blocks initial rendering做出react ?
在服务器端使用异步渲染之前(如果我看到上面的设置为true,那么我将不使用异步渲染).
我遗漏了什么概念吗?
Question 2:是我仅使用componentWillMount
就可以实现的任何其他用例,但不使用constructor
和componentDidMount
吗?