










在 React 15 中,生命周期函数主要分为 挂载(Mounting)、更新(Updating) 和 卸载(Unmounting) 三个阶段。以下是每个生命周期函数的详细说明及使用场景:
constructor(props)
state。this(如 this.handleClick = this.handleClick.bind(this))。componentWillMount()
render() 之前调用。constructor 类似,但由于服务端渲染时也会调用,且 React 17+ 将移除,建议将逻辑移到 constructor 或 componentDidMount。render()
null。props 和 state 描述 UI 结构。render 应为纯函数,不能修改 state 或执行副作用。componentDidMount()
componentWillUnmount 中取消订阅)。componentWillReceiveProps(nextProps)
props 时调用(首次渲染不会调用)。nextProps 更新 state(如将 props 同步到 state)。static getDerivedStateFromProps 替代,但在 React 15 中仍常用。shouldComponentUpdate(nextProps, nextState)
render 之前调用,决定是否跳过更新。props 和 state 避免不必要的渲染(如返回 false 阻止更新)。forceUpdate 时触发。componentWillUpdate(nextProps, nextState)
shouldComponentUpdate 返回 true 后、render 之前调用。setState,否则会陷入死循环。在 React 16.3+ 中已标记为不安全。render()
componentDidUpdate(prevProps, prevState)
prevProps 与当前 props 的差异来发起)。componentWillUnmount()
componentDidCatch(error, info)(React 16+ 引入,React 15 中不存在)挂载阶段:
constructor → componentWillMount → render → componentDidMount
更新阶段(props/state 变化):
componentWillReceiveProps → shouldComponentUpdate → componentWillUpdate → render → componentDidUpdate
卸载阶段:
componentWillUnmount
componentWillMount、componentWillReceiveProps、componentWillUpdate,并增加了 getDerivedStateFromProps、getSnapshotBeforeUpdate 等新生命周期。React 15 项目如需升级,需注意兼容性。componentWillMount 和 render 在服务端会被调用,而 componentDidMount 不会,因此涉及 DOM 的操作必须放在 componentDidMount 中。理解这些生命周期的执行时机和用途,可以帮助你更好地管理组件的状态、副作用和性能优化。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。