20200514

@czhang
  • date: 20200514
  • author: czhang

Plan

  1. react 生命周期应用
  2. hook 对应

Notes

  1. 初始化 state

    state = {
        a: this.props.a,
    };
    
  2. 获取外部数据

    • componentDidMount
  3. 添加事件监听器(或订阅)

    • componentDidMount 中订阅

    • componentWillUnmount 中 取消订阅

  4. 基于 props 更新 state

    1. 复制 prop 到子组件的 state 使用

      • 不安全 componentWillReceiveProps/getDerivedStateFromProps 会在父组件重新渲染的时候,再次调用,导致修改了的 state 变成了之前的。🌰
      • 改善:把子组件里面的设置 state 的 action 提升到父组件 => 变成受控组件
    2. 在 props 变化后修改 state

      • 在 componentWillReceiveProps 中 判断 nextProps.xx !== this.props.xxx 然后 setState
      • 在 getDerivedStateFromProps 中使用 props,state 来对比,此时要多存一个 state,记录上次的 props 的值
      class ExampleComponent extends React.Component {
          // 在构造函数中初始化 state,
          // 或者使用属性初始化器。
          state = {
              isScrollingDown: false,
              lastRow: null,
          };
      
          static getDerivedStateFromProps(props, state) {
              if (props.currentRow !== state.lastRow) {
                  return {
                      isScrollingDown: props.currentRow > state.lastRow,
                      lastRow: props.currentRow,
                  };
              }
      
              // 返回 null 表示无需更新 state。
              return null;
          }
      }
      
  5. 调用外部回调

    • 内部 state 变化时 调用外部 函数
      • 之前 在 componentWillUpdate 中对比操作
      • 之后 在 componentDidUpdate 中对比 (该生命周期能保证每次更新都只执行一次)
  6. props 更新的副作用

    • props 变化时 进行操作
      • 之前 在 componentWillReceiveProps 中对比操作
      • 之后 在 componentDidUpdate 中对比操作
  7. props 更新时获取外部数据

    • 2&6 组合
  8. 更新前读取 DOM 属性

    • 在 DOM 更新前获取信息,DOM 更新后设置属性
      • 之前 componentWillUpdate 中获取 DOM 属性,componentDidUpdate 中设置
      • 之后 getSnapshotBeforeUpdate 中获取 DOM 属性,componentDidUpdate 中设置

More

实践举例: