React生命周期

React 生命周期

React 生命周期分为三大阶段,挂载、更新、销毁


img.png

挂载阶段

constructor()

在安装 React 组件之前,会调用它的构造函数。

通常,在 React 中,构造函数仅用于两个目的:

  • 初始化数据this.state
  • 绑定 this 指向。
1
2
3
4
5
6
constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}

componentDidMount() 组件挂载完成

主要用于:

  • 获取异步数据,
  • 操作 dom 之类

render() 渲染

默认进来一次,后续如果有更新会再次触发


更新阶段

getDerivedStateFromProps()

能够让我们根据 props 的数据来设置 state 数据

  • 初始化 render 之前调用一次

  • 后续数据有变化,重新 render 之前又会调用

  • 不能使用 this.setState

  • 需要 return { } | null 如果是 { } ,会将这个 { } 与 state 合并

shouldComponentUpdate(nextProps, nextState)

可以用来性能优化,但是不常用

componentDidUpdate() 更新完成

componentDidUpdate() 更新发生后立即调用。初始渲染不会调用此方法。

将此作为在更新组件时对 DOM 进行操作的机会。只要您将当前道具与之前的道具进行比较(例如,如果道具未更改,则可能不需要网络请求),这也是进行网络请求的好地方。

1
2
3
4
5
6
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}

销毁阶段

componentWillUnmount()

componentWillUnmount() 在卸载和销毁组件之前立即调用。在此方法中执行任何必要的清理,例如使计时器无效,取消网络请求或清除在其中创建的任何订阅 componentDidMount()。

-------------本文结束感谢您的阅读-------------
0%