React组件的生命周期是指组件从创建、挂载到更新、卸载的完整过程,通过生命周期钩子函数(生命周期方法),开发者可以在特定阶段插入自定义逻辑(如初始化状态、操作DOM、清理资源等)。
需要注意的是:函数组件没有生命周期,但可通过React Hooks(如useEffect)模拟类似功能;以下内容均针对类组件展开。
React组件的生命周期主要分为三大阶段,每个阶段包含若干关键钩子函数:
定义:组件从实例化到首次渲染到真实DOM的过程(“出生”阶段)。
触发时机:ReactDOM.render(<Component />, container)。
关键钩子函数及作用:
constructor(props)state(如this.state = { count: 0 });this指向(如this.handleClick = this.handleClick.bind(this));props(通过props参数)。super(props)(ES6类的要求,用于初始化父类的props);constructor中调用setState(此时组件未挂载,无法触发渲染)。static getDerivedStateFromProps(props, state)constructor之后、render之前(每次渲染前都会执行,包括首次渲染和更新)。props**更新组件的state(返回一个对象,React会将其合并到state中;返回null则表示不更新)。static修饰),无法访问this;props直接控制渲染。render()state或触发DOM操作)。<div />、null或false);setState(会导致无限循环渲染)。componentDidMount()render之后(组件首次渲染到真实DOM后执行,仅一次)。this.refs或document.getElementById访问DOM节点;定义:组件因props变化、state更新或forceUpdate触发的重新渲染过程(“成长”阶段)。
触发时机:
props);this.setState修改state;this.forceUpdate强制更新。static getDerivedStateFromProps(props, state)props更新state)。render配合使用(每次渲染前都会执行),避免复杂的逻辑。shouldComponentUpdate(nextProps, nextState)getDerivedStateFromProps之后、render之前。true则继续更新流程,返回false则跳过本次更新)。true,每次props或state变化都会触发更新);nextProps和nextState与当前的this.props、this.state(避免浅比较导致的bug)。render()setState(会导致无限循环)。getSnapshotBeforeUpdate(prevProps, prevState)render之后、componentDidUpdate之前。componentDidUpdate的第三个参数)。componentDidUpdate配合使用(返回值会被传递给componentDidUpdate);componentDidUpdate(prevProps, prevState, snapshot)props获取数据、操作更新后的DOM、发送分析事件等)。prevProps和prevState与当前的this.props、this.state(避免不必要的操作);setState(可能导致无限循环,除非配合条件判断)。定义:组件从DOM中移除的过程(“死亡”阶段)。
触发时机:ReactDOM.unmountComponentAtNode(container)或父组件卸载时。
关键钩子函数及作用:
componentWillUnmount()setState(组件已卸载,无法更新状态)。定义:组件渲染、生命周期或子组件构造函数中抛出错误时的处理阶段。
关键钩子函数及作用:
static getDerivedStateFromError(error)state(如设置hasError: true),用于显示错误边界UI。this;componentDidCatch(error, info)getDerivedStateFromError之后执行。getDerivedStateFromError配合使用,构成错误边界(Error Boundary)。constructor → getDerivedStateFromProps → render → componentDidMount
setState触发)getDerivedStateFromProps → shouldComponentUpdate → render → getSnapshotBeforeUpdate → componentDidUpdate
componentWillUnmount
componentWillMount、componentWillReceiveProps、componentWillUpdate被标记为不安全(UNSAFE_前缀),建议使用getDerivedStateFromProps、componentDidUpdate替代。useEffect模拟:
componentDidMount → useEffect(() => {}, [])(空依赖数组,仅在挂载时执行);componentDidUpdate → useEffect(() => {}, [props, state])(依赖项变化时执行);componentWillUnmount → useEffect(() => { return () => {} }, [])(返回清理函数)。shouldComponentUpdate或React.memo(函数组件)避免不必要的渲染;render中执行复杂计算(可使用useMemo缓存结果)。通过以上详解,可清晰掌握React类组件生命周期的各个阶段及钩子函数的使用场景,为组件开发提供更精准的控制能力。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。