React17.0生命周期调整
在即将到来的react17.0版本,react团队对生命周期做了调整,将会移除 componentWillMount,componentWillReceiveProps,componentWillUpdate这三个生命周期,因为这些生命周期方法容易被误解和滥用。
组件数据初始化
一般我们为了提前 setState ,防止二次渲染(第一次是空state渲染,第二次外部数据渲染),经常在 componentWillMount
生命周期请求数据
// Before
class ExampleComponent extends React.Component {
state = {
externalData: null,
};
componentWillMount() {
this._asyncRequest = asyncLoadData().then(
externalData => {
this._asyncRequest = null;
this.setState({
externalData});
}
);
}
componentWillUnmount() {
if (this._asyncRequest) {
this._asyncRequest.cancel();
}
}
render() {
if (this.state.externalData === null) {
// Render loading state ...
} else {
// Render real UI ...
}
}
}
但是事实却不是这样的,异步获取外部数据不一定会在渲染之前返回,这也意味着组件也有可能会被渲染一次,为了后面新版本实现异步渲染,建议请求放在 componentDidMount
来调用。
还有一个问题是,componentWillMount
在服务端渲染(nuxt.js)的时候会导致服务端和客户端各渲染一次,而 componentDidMount
只在客户端渲染一次
// After
class ExampleComponent extends React.Component {
state = {
externalData: null,
};
componentDidMount() {
this._asyncRequest = loadMyAsyncData().then(
externalData => {
this._asyncRequest = null;
this.setState({
externalData});
}
);
}
componentWillUnmount() {
if (this._asyncRequest) {
this._asyncRequest.cancel();
}
}
render() {
if (this.state.externalData === null) {