在 React.Component 的子类中有个必须定义的 render() 函数。其他方法均为可选。
挂载
- constructor ()
- static getDerivedStateFromProps()
- render()
- componentDidMount()
更新
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
卸载
-
componentWillUnmout()
加粗为常用的生命周期
常用生命周期
render()
- render()是 class 组件中唯一必须实现的方法。
- render() 函数应该为纯函数。
- 如果 shouldComponentUpdate() 返回 false,则不会调用 render()。
constructor()
constructor(props)
- 如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。
- 通过给 this.state 赋值对象来初始化内部 state。
- 为事件处理函数绑定实例
constructor(props) { super(props); // 不要在这里调用 this.setState() this.state = { counter: 0 }; this.handleClick = this.handleClick.bind(this); }
componentDidMount()
组件挂载后立即调用,比较适合添加订阅、网络请求数据
componentDidUpdate()
componentDidUpdate(prevProps, prevState, snapshot)
componentWillUnmount()
清除 timer,取消网络请求或清除在 componentDidMount() 中创建的订阅等
不常用生命周期
shouldComponentUpdate()
shouldComponentUpdate(nextProps, nextState)
- 首次渲染或使用 forceUpdate() 时不会调用该方法。
- 仅作为性能优化的方式而存在, 不要依靠此方法来“阻止”渲染
- 返回 false,则不会调用 UNSAFE_componentWillUpdate(),render() 和 componentDidUpdate()
static getDerivedStateFromProps()
static getDerivedSstateFromProps(props, state)
getSnapshotBeforeUpdate()
在最近一次渲染输出(提交到 DOM 节点)之前调用。它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)