React 学习笔记 —— 组件生命周期(包含17新版和旧版对比)
发布日期:2021-05-12 21:18:31 浏览次数:19 分类:精选文章

本文共 3955 字,大约阅读时间需要 13 分钟。

生命周期优化是React开发中一个核心的概念,理解它能帮助开发者更好地管理组件的状态和渲染流程。本文将深入探讨React组件的生命周期,并结合实际案例,阐述如何在不同场景下优化组件的更新和卸载流程。

React 组件生命周期概述

React 组件生命周期可以分为三个主要阶段:

1. 初始化阶段

初始化阶段从ReactDOM.render()触发,通常由componentDidMount标记。该阶段包括以下关键步骤:

  • constructor(): 在组件实例化时执行,通常用于初始化初始状态。
  • componentWillMount(): 组件将要挂载时执行,适用于初始化数据或设置定时器。
  • render(): 首次渲染或更新渲染时调用,负责将组件转换为最初的 JSX 结构。
  • componentDidMount(): 组件挂载完成时执行,通常用于发送网络请求或设置 DOM 事件监听。

2. 更新阶段

更新阶段由组件内部的this.setState()或父组件的render()重新渲染触发,主要流程包括:

  • shouldComponentUpdate(): 检查是否需要更新,返回false可跳过渲染。
  • componentWillUpdate(): 组件将要更新时执行,适用于权限检查或数据处理。
  • render(): 渲染过程,类似于初始化阶段。
  • componentDidUpdate(): 组件更新完成时执行,可用于状态恢复或 DOM 更新。

3. 卸载阶段

卸载阶段由ReactDOM.unmountComponentAtNode()触发,主要步骤包括:

  • componentWillUnmount(): 组件将要卸载时执行,常用于清理定时器或释放资源。

React 组件生命周期优化实例

以下是几个基于生命周期优化的常见场景:

####_SCENE 1: 首次渲染优化

在初始化阶段,开发者应尽量减少render()方法中逻辑的复杂度,避免在初始渲染和更新阶段重复执行时间敏感的操作。例如:

class Demo extends React.Component {
constructor() {
super();
this.state = { count: 0 };
console.log('constructor');
}
componentWillMount() {
console.log('componentWillMount');
}
render() {
console.log('render');
return (
{this.state.count}
);
}
componentDidMount() {
console.log('componentDidMount');
}
}

####_SCENE 2: 状态更新优化

在更新阶段,为了避免不必要的渲染,建议在shouldComponentUpdate()中进行增量性检查。如:

class Demo extends React.Component {
constructor() {
super();
this.state = { count: 0 };
console.log('constructor');
}
shouldComponentUpdate() {
console.log('shouldComponentUpdate');
return true;
}
// 其他回调函数保持不变
}

####_SCENE 3: 强制更新

在某些情况下,开发者需要强制触发更新而不经setState。可以借助forceUpdate()方法:

class Demo extends React.Component {
constructor() {
super();
this.state = { count: 0 };
console.log('constructor');
}
render() {
console.log('render');
return (
{this.state.count}
);
}
}

####parent组件和子组件的交互

React 17 版本更新

React 17 版本对生命周期模型进行了重要调整:

####废弃的钩子函数

React公告称三个钩子将被废弃:

  • componentWillReceiveProps
  • componentWillMount
  • componentWillUpdate

替代方案:

  • 使用新的UNSAFE_前缀命名:
    • UNSAFE_componentWillReceiveProps
    • UNSAFE_componentWillMount
    • UNSAFE_componentWillUpdate

新增钩子函数

React 17 引入了两个新的钩子:

  • getDerivedStateFromProps: 从 props 中获取派生的状态。
  • getSnapshotBeforeUpdate: 在更新前获取快照。

new钩子函数示例

class Demo extends React.Component {
static getDerivedStateFromProps(props, state) {
console.log('getDerivedStateFromProps');
return null;
}
render() {
console.log('render');
return (
{this.props.count}
);
}
// 其他回调函数保持不变
}

getSnapshotBeforeUpdate 示例

以下是一个使用 getSnapshotBeforeUpdate 的简单示例:

import React from 'react';
class NewsList extends React.Component {
state = { newsArr: [] };
ref = React.createRef();
componentDidMount() {
setInterval(() => {
const news = `新闻${this.state.newsArr.length + 1}`;
this.setState({ newsArr: [news, ...this.state.newsArr] });
}, 1000);
console.log('componentDidMount');
}
getSnapshotBeforeUpdate(prevProps, prevState) {
return this.ref.current.scrollHeight;
}
componentDidUpdate(prevProps, prevPk, prevPstate, snapshot) {
console.log('componentDidUpdate');
this.ref.current.scrollTop += this.ref.current.scrollHeight - snapshot;
}
render() {
return (
{this.state.newsArr.map((n, index) => (
{n}
))}
);
}
}

总结

通过上述分析,可以看出 React 组件的生命周期优化对提升应用性能和开发体验至关重要。在实际开发中,应根据项目需求合理选择生命周期钩子,并采用合适的优化策略,以确保组件的高效运行和良好的用户体验。

上一篇:React 学习笔记 —— css 样式的模块化
下一篇:React学习笔记——在受控组件中使用函数柯里化

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年04月07日 12时05分36秒