React的生命周期方法在不同版本中有所变化,尤其是在React 16.3版本引入新的生命周期方法和在React 16.8引入Hooks后。下面是根据不同版本的React组件生命周期阶段、执行顺序、使用场景以及对应的方法的概览。
React 16.3之前的生命周期
挂载阶段(Mounting)
- 执行顺序:
constructor()->componentWillMount()->render()->componentDidMount() - 使用场景:
constructor(): 初始化state和绑定事件处理器。componentWillMount(): 在服务器端渲染中使用,因为它在渲染前调用。在React 16.3之后被废弃。render(): 唯一必须实现的方法,返回需要渲染的React元素。componentDidMount(): 执行DOM操作,发送网络请求,设置事件监听器。
更新阶段(Updating)
- 执行顺序:
componentWillReceiveProps()->shouldComponentUpdate()->componentWillUpdate()->render()->componentDidUpdate() - 使用场景:
componentWillReceiveProps(): 接收新的props之前调用。在React 16.3之后被废弃。shouldComponentUpdate(): 决定是否重新渲染组件。componentWillUpdate(): 在重新渲染前调用。在React 16.3之后被废弃。render(): 重新渲染UI。componentDidUpdate(): 更新DOM操作,发送网络请求。
卸载阶段(Unmounting)
- 执行顺序:
componentWillUnmount() - 使用场景: 清理操作,如取消网络请求、移除事件监听器。
React 16.3及之后的生命周期
挂载阶段(Mounting)
- 执行顺序:
constructor()->static getDerivedStateFromProps()->render()->componentDidMount() - 使用场景:
getDerivedStateFromProps(): 替代componentWillReceiveProps,在初始化和接收新props时更新state。- 其他方法使用场景与16.3之前相同。
更新阶段(Updating)
- 执行顺序:
static getDerivedStateFromProps()->shouldComponentUpdate()->render()->getSnapshotBeforeUpdate()->componentDidUpdate() - 使用场景:
getSnapshotBeforeUpdate(): 替代componentWillUpdate,捕获更新前的DOM状态(如滚动位置)。
卸载阶段(Unmounting)
- 使用场景与16.3之前相同。
React 16.8及之后的Hooks
React 16.8引入Hooks,为函数组件提供了类似于类组件生命周期方法的能力,但使用方式不同。
- Hooks:
useState,useEffect,useContext,useReducer,useCallback,useMemo,useRef - 使用场景:
useState和useReducer用于状态管理。useEffect用于处理副作用,可以模拟componentDidMount,componentDidUpdate, 和componentWillUnmount的行为。useContext,useCallback,useMemo,useRef提供了上下文共享、记忆化计算和引用直接DOM元素的能力。
使用场景概览
- 初始化和挂载:设置初始状态,进行首次渲染,设置DOM引用。
- 接收新的props和更新:响应状态或props的变化,决定组件渲染逻辑,执行与渲染前后相关的操作。
- 卸载:执行清理工作,如取消订阅和定时器,移除事件监听器。
React的生命周期方法和Hooks提供了丰富的API来处理组件的创建、更新和销毁过程,帮
助开发者管理组件的状态和生命周期事件。