【问题标题】:How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps如何使用生命周期方法 getDerivedStateFromProps 而不是 componentWillReceiveProps
【发布时间】:2018-09-12 00:53:06
【问题描述】:

看起来componentWillReceiveProps 将在即将发布的版本中完全淘汰,取而代之的是新的生命周期方法getDerivedStateFromProps:static getDerivedStateFromProps()

经检查,您现在无法像在 componentWillReceiveProps 中那样直接比较 this.propsnextProps。有没有办法解决这个问题?

此外,它现在返回一个对象。我是否正确假设返回值本质上是this.setState

下面是我在网上找到的一个例子:State derived from props/state.

之前

class ExampleComponent extends React.Component {
  state = {
    derivedData: computeDerivedState(this.props)
  };

  componentWillReceiveProps(nextProps) {
    if (this.props.someValue !== nextProps.someValue) {
      this.setState({
        derivedData: computeDerivedState(nextProps)
      });
    }
  }
}

之后

class ExampleComponent extends React.Component {
  // Initialize state in constructor,
  // Or with a property initializer.
  state = {};

  static getDerivedStateFromProps(nextProps, prevState) {
    if (prevState.someMirroredValue !== nextProps.someValue) {
      return {
        derivedData: computeDerivedState(nextProps),
        someMirroredValue: nextProps.someValue
      };
    }

    // Return null to indicate no change to state.
    return null;
  }
}

【问题讨论】:

  • 标题应该是“尽管 React 团队竭尽全力反对它,但如何让事情顺利进行”

标签: javascript reactjs lifecycle


【解决方案1】:

关于删除componentWillReceiveProps:您应该能够通过getDerivedStateFromPropscomponentDidUpdate 的组合来处理它的使用,请参阅the React blog post 示例迁移。是的,getDerivedStateFromProps 返回的对象更新状态类似于传递给setState 的对象。

如果你真的需要一个 prop 的旧值,你可以随时将它缓存在你的状态中,如下所示:

state = {
  cachedSomeProp: null
  // ... rest of initial state
};

static getDerivedStateFromProps(nextProps, prevState) {
  // do things with nextProps.someProp and prevState.cachedSomeProp
  return {
    cachedSomeProp: nextProps.someProp,
    // ... other derived state properties
  };
}

任何不影响状态的东西都可以放在componentDidUpdate,甚至还有一个getSnapshotBeforeUpdate 用于非常低级别的东西。

更新:要了解新的(和旧的)生命周期方法,react-lifecycle-visualizer 包可能会有所帮助。

【讨论】:

  • 呃,我把问题搞砸了。我的意思是componentWillReceiveProps
  • 我曾想过使用我的状态来保存以前的道具,但我真的想避免实现它所需的额外代码和逻辑。我会调查你提出的其他一些事情。非常感谢!
  • 必须将先前的 prop 存储在一个 state 中只是这个难以理解的 React API 更改的样板解决方法。在许多开发人员的眼中,这看起来像是一种反模式和一种回归变化。不是批评你 Oblosys,而是批评 React 团队。
  • @AxeEffect 这是因为 getDerivedStateFromProps 从未真正用于记忆​​>。请在下面查看我的回答,其中我描述了推荐的方法
  • 是错字吗?你错过...了吗?那就是我们应该返回整个状态对象还是只返回我们关心的部分。
【解决方案2】:

正如我们recently posted on the React blog在绝大多数情况下你根本不需要getDerivedStateFromProps

如果您只想计算一些派生数据,则:

  1. render 内部进行操作
  2. 或者,如果重新计算代价高昂,请使用诸如 memoize-one 之类的记忆化助手。

这是最简单的“之后”示例:

import memoize from "memoize-one";

class ExampleComponent extends React.Component {
  getDerivedData = memoize(computeDerivedState);

  render() {
    const derivedData = this.getDerivedData(this.props.someValue);
    // ...
  }
}

查看 this section of the blog post 了解更多信息。

【讨论】:

  • 如果在广大大多数情况下不需要它,那么我很惊讶这是一个如此急需的改变,它会破坏成千上万的工作项目。看起来 React 团队是从工程开始的。
  • 从 componentWillReceiveProps 更改为 getDerivedStateFromProps。它不是破坏而是强制重构所有现有代码,这非常耗时。而且似乎没有什么好处,因为您说在绝大多数情况下根本不应该使用它。为什么要为一开始就不应该使用的东西更改 API 的麻烦。
  • 我很想回复 Dan Abramov 的评论。
  • @DanAbramov 关于为什么会发生这种变化的任何答案?
  • 其实在我们的项目中这个用的很多。当新数据出现时,在屏幕上显示诸如 Snackbars 之类的东西,1 个示例。 componentWillReceiveProps 很简单而且很有效。为什么要为这个静态垃圾删除它...
【解决方案3】:

正如丹·阿布拉莫夫所说

在渲染中直接做

我们实际上将这种方法与 memoise one 一起用于任何类型的代理道具以进行状态计算。

我们的代码是这样的

// ./decorators/memoized.js  
import memoizeOne from 'memoize-one';

export function memoized(target, key, descriptor) {
  descriptor.value = memoizeOne(descriptor.value);
  return descriptor;
}

// ./components/exampleComponent.js
import React from 'react';
import { memoized } from 'src/decorators';

class ExampleComponent extends React.Component {
  buildValuesFromProps() {
    const {
      watchedProp1,
      watchedProp2,
      watchedProp3,
      watchedProp4,
      watchedProp5,
    } = this.props
    return {
      value1: buildValue1(watchedProp1, watchedProp2),
      value2: buildValue2(watchedProp1, watchedProp3, watchedProp5),
      value3: buildValue3(watchedProp3, watchedProp4, watchedProp5),
    }
  }

  @memoized
  buildValue1(watchedProp1, watchedProp2) {
    return ...;
  }

  @memoized
  buildValue2(watchedProp1, watchedProp3, watchedProp5) {
    return ...;
  }

  @memoized
  buildValue3(watchedProp3, watchedProp4, watchedProp5) {
    return ...;
  }

  render() {
    const {
      value1,
      value2,
      value3
    } = this.buildValuesFromProps();

    return (
      <div>
        <Component1 value={value1}>
        <Component2 value={value2}>
        <Component3 value={value3}>
      </div>
    );
  }
}

它的好处是您无需在 getDerivedStateFromPropscomponentWillReceiveProps 内编写大量比较样板代码,并且您可以跳过构造函数内的复制粘贴初始化。

注意:

这种方法仅用于将 props 代理为 state,以防你有一些内部状态逻辑,它仍然需要在组件生命周期中处理。

【讨论】:

    【解决方案4】:

    getDerivedStateFromProps 用于在渲染之前更新状态并使用 props 的条件进行更新

    GetDerivedStateFromPropd 借助 props 值更新 stats 值

    阅读https://www.w3schools.com/REACT/react_lifecycle.asp#:~:text=Lifecycle%20of%20Components,Mounting%2C%20Updating%2C%20and%20Unmounting

    【讨论】:

      猜你喜欢
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多