React · 45/84
1. 为什么推荐将静态资源放到 CDN 上 2. Class 组件的局限性 3. Class 组件与函数组件 4. Composition API 与 Hooks 对比 5. Vue 中 computed 和 watch 的区别 6. 爬楼梯问题 7. createElement 执行过程 8. 限制构造函数只能通过 new 调用 9. 判断 React 组件类型 10. 受控与非受控组件 11. 自定义 Hook 开发 12. 什么是 DNS 劫持? 13. 判断对象是否是 React 元素 14. HOC 与 Render Props 15. React 中 Element、Component、Node、Instance 的区别 16. Hooks 使用规则 17. HTTP/2 多路复用原理 18. HTTP 报文结构 19. HTTPS 握手过程 20. Immutable 在 React 中的应用 21. 实现图片懒加载 22. JavaScript == 运算符的机制 23. JavaScript 数组的内存存储方式 24. JSX 本质 25. Immutable 在 React 中的应用 26. 最大子序和 27. React Router 的 Link 和 a 标签的区别 28. JSX语法糖本质 29. 父组件调用子组件方法 30. 移动端样式适配方案 31. Portal 中的事件冒泡机制 32. React 17 新特性 33. React 18 新特性与并发渲染 34. React 组件渲染流程 35. React 是什么 36. React元素$$typeof属性 37. React 组件通信方式 38. React 错误边界处理 39. React 核心概念 40. React 组件设计 41. React Fiber 架构 42. React Hooks 原理与规则 43. React 常用 Hooks 使用指南 44. React.memo 和 memoize 函数的区别 45. React 生命周期演变 46. React 性能优化实践 47. React 性能优化策略 48. React Portals 的使用场景 49. React 中的 ref 使用 50. React 和 React-DOM 的关系 51. React 为什么不直接使用 requestIdleCallback 52. React-Router 原理与工作方式 53. React 合成事件机制 54. React 服务端渲染实现 55. React 事务机制 56. setState 同步异步问题 57. setTimeout 为什么不能保证及时执行 58. Redux 工作流与中间件 59. React 服务端渲染实现 60. 单页应用如何提高加载速度 61. Source Map 的工作原理 62. TypeScript 中的命名空间与模块 63. Taro 多端框架实现原理 64. Taro 2.x 和 Taro 3 的区别 65. TypeScript 与 JavaScript 的区别 66. TCP 三次握手和四次挥手 67. useEffect 支持 async/await 68. useEffect 闭包陷阱 69. useMemo 和 useCallback 的使用场景 70. useContext 的使用方法 71. useReducer 与 Redux 对比 72. useState 连续调用 setState 导致值丢失 73. 实现 useTimeout Hook 74. useRef、ref 和 forwardRef 的区别 75. 虚拟DOM性能分析 76. 实现 useUpdate 强制组件重新渲染 77. Virtual DOM 的意义 78. 虚拟DOM的三个组成部分 79. Virtual DOM 与 Diff 算法 80. Vue 页面渲染流程 81. Vue 与 React 对比 82. Vue 与 React 的 Diff 算法差异 83. Vue2 数组变化检测的限制与解决方案 84. Vue3 实现 Modal 组件

React 生命周期演变

对比 React 旧版 Will 系列与新版生命周期方法

问题

React 16.3 废弃了 componentWillMountcomponentWillReceivePropscomponentWillUpdate 三个生命周期方法,引入了 getDerivedStateFromPropsgetSnapshotBeforeUpdate。为什么要这样改?新旧方法如何对应?

解答

旧版生命周期(已废弃)

class OldLifecycle extends React.Component {
  // 组件挂载前调用,在 render 之前
  componentWillMount() {
    // 问题:在这里发起异步请求,可能导致多次渲染
    // 在 SSR 中会执行两次
  }

  // 接收新 props 时调用
  componentWillReceiveProps(nextProps) {
    // 问题:父组件重新渲染就会触发,即使 props 没变
    if (nextProps.id !== this.props.id) {
      this.setState({ data: null });
      this.fetchData(nextProps.id);
    }
  }

  // 更新前调用
  componentWillUpdate(nextProps, nextState) {
    // 问题:在 Fiber 架构下可能被多次调用
    // 读取 DOM 信息可能不准确
  }
}

废弃原因

React Fiber 引入了异步渲染,render 阶段可能被中断、暂停、重新执行。Will 系列方法在 render 阶段执行,存在以下问题:

  1. 可能被多次调用:异步渲染下,render 阶段的方法可能执行多次
  2. 副作用不安全:在这些方法中发起请求、订阅事件会导致重复执行
  3. DOM 读取不可靠componentWillUpdate 读取的 DOM 状态可能与最终提交时不一致

新版生命周期

class NewLifecycle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      prevId: props.id,
      data: null
    };
    this.listRef = React.createRef();
  }

  // 静态方法,在 render 前调用
  // 返回值用于更新 state,返回 null 表示不更新
  static getDerivedStateFromProps(nextProps, prevState) {
    // 替代 componentWillReceiveProps
    // 注意:无法访问 this,无法执行副作用
    if (nextProps.id !== prevState.prevId) {
      return {
        prevId: nextProps.id,
        data: null // 标记需要重新获取数据
      };
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // 数据获取移到这里
    if (this.state.data === null) {
      this.fetchData(this.props.id);
    }

    // snapshot 来自 getSnapshotBeforeUpdate
    if (snapshot !== null) {
      this.listRef.current.scrollTop += 
        this.listRef.current.scrollHeight - snapshot;
    }
  }

  // 在 DOM 更新前调用,返回值传给 componentDidUpdate
  getSnapshotBeforeUpdate(prevProps, prevState) {
    // 替代 componentWillUpdate 中的 DOM 读取
    // 在 commit 阶段调用,保证 DOM 读取准确
    if (prevProps.list.length < this.props.list.length) {
      return this.listRef.current.scrollHeight;
    }
    return null;
  }

  render() {
    return <div ref={this.listRef}>{/* ... */}</div>;
  }
}

生命周期对照表

旧版方法新版替代方案
componentWillMountconstructor + componentDidMount
componentWillReceivePropsgetDerivedStateFromProps + componentDidUpdate
componentWillUpdategetSnapshotBeforeUpdate + componentDidUpdate

完整生命周期顺序

// 挂载阶段
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()

// 更新阶段
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()

// 卸载阶段
componentWillUnmount()

迁移示例:滚动位置保持

// 旧版写法(有问题)
class OldList extends React.Component {
  componentWillUpdate(nextProps) {
    if (nextProps.items.length > this.props.items.length) {
      // 问题:读取的 scrollHeight 可能不准确
      this.previousScrollHeight = this.listRef.scrollHeight;
    }
  }

  componentDidUpdate() {
    if (this.previousScrollHeight) {
      // 保持滚动位置
      this.listRef.scrollTop += 
        this.listRef.scrollHeight - this.previousScrollHeight;
    }
  }
}

// 新版写法(推荐)
class NewList extends React.Component {
  getSnapshotBeforeUpdate(prevProps) {
    if (prevProps.items.length < this.props.items.length) {
      // 在 DOM 更新前读取,保证准确
      return this.listRef.current.scrollHeight;
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (snapshot !== null) {
      this.listRef.current.scrollTop += 
        this.listRef.current.scrollHeight - snapshot;
    }
  }
}

关键点

  • 废弃原因:Fiber 异步渲染下,render 阶段方法可能被多次调用,副作用不安全
  • getDerivedStateFromProps 是静态方法,无法访问 this,强制避免副作用
  • getSnapshotBeforeUpdate 在 commit 阶段调用,保证 DOM 读取准确
  • 副作用迁移:数据获取、订阅等操作应放在 componentDidMountcomponentDidUpdate
  • 渐进迁移:旧方法加 UNSAFE_ 前缀仍可使用,但会在 React 18 严格模式下警告