react 类组件生命周期
时间: 2023-09-05 21:07:37 浏览: 189
React 类组件生命周期可以分为三个阶段:挂载、更新和卸载。
1. 挂载阶段:
- constructor():组件的构造函数,在组件创建时调用,通常用于初始化 state 和绑定事件处理方法。
- static getDerivedStateFromProps():静态方法,当组件接收到新的 props 时调用,在 render() 方法之前调用,可用于根据新的 props 更新 state。
- render():渲染组件的界面,必须实现的方法。
- componentDidMount():组件挂载完成后调用,通常用于进行异步操作,如数据获取等。
2. 更新阶段:
- static getDerivedStateFromProps():同挂载阶段。
- shouldComponentUpdate():组件更新前调用,返回布尔值,决定是否重新渲染组件,默认返回 true。
- render():同挂载阶段。
- componentDidUpdate():组件更新后调用,通常用于进行组件更新后的操作,如重新获取数据等。
3. 卸载阶段:
- componentWillUnmount():组件卸载前调用,通常用于进行资源的清理和事件的解绑。
另外,还有一些被废弃或不常用的生命周期方法,如 UNSAFE_componentWillMount()、componentWillReceiveProps()、UNSAFE_componentWillUpdate() 等。我们应尽量避免使用这些方法,以免造成不必要的 bug 和维护成本。
阅读全文
相关推荐















