React类组件生命周期
本文主要探讨React中的是生命周期及其应用。
class组件的生命周期
React组件生命周期主要分为3个阶段:
1.组件挂载(mount)阶段
2.组件更新(update)阶段
3.组件卸载(unmount)阶段
生命周期函数
static getDerivedStateFromProps
一个静态方法,每次render前都会调用,你可以返回一个对象用于更新state,如果返回null将不更新。
这个生命周期的主要作用是当props发生变化时,更新你的state。
有一个已废弃的生命周期方法componentWillReceiveProps,用于props发生变化时更新state, 现在可完全用getDerivedStateFromProps取代其功能。
static getDerivedStateFromProps(props, state) {
if (props.id !== state.id) {
return {
id: props.id,
username: props.username
};
}
return null
}
componentDidMount
这个方法会在组件对应的元素出现在屏幕上后调用,此时可以获取到DOM节点,通常用于获取网络数据、操纵DOM节点。
Q:为什么数据请求不放在componentWillMount中(已标记为unsafe)?
A:
1.从性能上,不会有明显的提升(请求早发出的时间几乎可以忽略不计)
2.服务端渲染会执行两次,容易给开发者造成困扰。
async componentDidMount() {
// 请求网络数据
const res = await requestFn();
if (res.result.code === 0) {
this.setState({ data: res.data });
}
}
shouldComponentUpdate
这个生命周期方法在re-render(更新时引起的render)前触发,你可以返回一个bool值用于确定此次更新是否跳过,如果返回值为true,则更新继续。
通常用于props派生state的场景,此时组件为非受控组件,然而这么做可能会引来很多问题。
shouldComponentUpdate(nextpProps, nextState) {
if (nextProps.id === this.props.id) {
return false;
}
return true;
}
getSnapshotBeforeUpdate
这个生命周期在react更新DOM前调用,可以返回一个snapshot值,作为componentDidUpdate的第三个入参数。
这个函数使用的比较少,通常会用于
componentDidUpdate
这个方法会在组件对应的元素更新后调用,此时可以获取到DOM节点,通常用于获取网络数据、操纵DOM节点。
componentDidUpdate(prevProps, prevState) {}
componentWillUnmount
componentWillUnmount这个方法会在组件即将卸载前调用, 通常用于一些监听事件或者定期器的卸载,避免内存泄漏。
废弃的方法componentWillMount & componentWillUpdate
这些方法已被弃用,新代码不在推荐使用,这些生命周期方法没有不可替代性。
例如:componentWillMount这个方法会在constructor后立即调用,新代码已经不建议使用。
react文档给出的解释:
1.如果是初始化state,使用constructor
2.如果需要执行副作用,使用componentDidMount
简单来说这个生命周期没有不可替代性了,做减法,避免让开发者去选择。