返回

React getDerivedStateFromProps 生命周期

前端

理解 getDerivedStateFromProps

React 生命周期的命名一直都非常语义化,这个生命周期的意思就是从 props 中获取 state,可以说是太简单易懂了。

可以这么说,这个生命周期的功能实际上就是将传入的 props 映射到 state 上面。

意味着即使你的 props 没有发生任何变化,而是父 state 发生了变化,导致子组件发…

getDerivedStateFromProps 的用法

getDerivedStateFromProps 函数接受两个参数:

  • props:组件的 props 对象
  • state:组件的 state 对象

getDerivedStateFromProps 函数应该返回一个对象,该对象包含要更新的 state 属性。

例如,以下代码示例展示了如何使用 getDerivedStateFromProps 函数来将 props 中的 username 映射到 state 中的 username:

class MyComponent extends React.Component {
  static getDerivedStateFromProps(props, state) {
    return {
      username: props.username
    };
  }

  render() {
    return (
      <div>
        <h1>{this.state.username}</h1>
      </div>
    );
  }
}

getDerivedStateFromProps 的注意事项

  • getDerivedStateFromProps 函数只能在类组件中使用,函数组件无法使用。
  • getDerivedStateFromProps 函数在组件的第一次渲染之前以及每次 props 更新之前调用。
  • getDerivedStateFromProps 函数应该返回一个对象,该对象包含要更新的 state 属性。
  • getDerivedStateFromProps 函数不能直接修改 state,而应该通过返回一个对象来更新 state。
  • getDerivedStateFromProps 函数可以用来处理 props 中的变化,并相应地更新 state。
  • getDerivedStateFromProps 函数可以用来对 props 进行验证,并根据验证结果来更新 state。

替代方案

在 React 16.8 版本中,引入了新的生命周期函数 useMemo,它可以替代 getDerivedStateFromProps 函数来实现类似的功能。

useMemo 函数接受两个参数:

  • 一个函数,该函数返回要计算的值
  • 一个依赖项数组,当依赖项数组中的任何值发生变化时,useMemo 函数就会重新计算并返回新的值

以下代码示例展示了如何使用 useMemo 函数来实现 getDerivedStateFromProps 函数的功能:

const MyComponent = () => {
  const username = useMemo(() => {
    return props.username;
  }, [props.username]);

  return (
    <div>
      <h1>{username}</h1>
    </div>
  );
};

useMemo 函数的优点在于它可以避免在每次 props 更新时都重新计算 state,从而提高了组件的性能。

总结

getDerivedStateFromProps 函数是一个非常有用的生命周期函数,它可以用来从 props 中获取 state,并根据 props 的变化来更新 state。

在 React 16.8 版本中,引入了新的生命周期函数 useMemo,它可以替代 getDerivedStateFromProps 函数来实现类似的功能。

useMemo 函数的优点在于它可以避免在每次 props 更新时都重新计算 state,从而提高了组件的性能。