【问题标题】:Why use getDerivedStateFromProps when you have componentDidUpdate?为什么在有 componentDidUpdate 时使用 getDerivedStateFromProps?
【发布时间】:2018-04-27 02:37:41
【问题描述】:

我对 react 16 的新生命周期 getDerivedStateFromProps 用例感到困惑。以下面的代码为例,getDerivedStateFromProps 根本不需要,因为我可以通过 componentDidUpdate 实现我想要的。

export class ComponentName extends Component {
  //what is this for?
  static getDerivedStateFromProps(nextProps, prevState) {

    if (nextProps.filtered !== prevState.filtered && nextProps.filtered === 'updated') {
      return {
        updated: true //set state updated to true, can't do anything more?
      };
    }

    return null;

  }

  componentDidUpdate(prevProps, prevState) {
    if(prevProps.filtered !== this.state.filtered && this.state.filtered === 'updated'){
      console.log('do something like fetch api call, redirect, etc..')
    }
  }

  render() {
    return (
      <div></div>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    来自this article

    随着componentWillReceiveProps 被删除,我们需要一些方法来根据道具变化更新状态 — 社区决定引入一种新的 — 静态 — 方法来处理这个问题。

    什么是静态方法?静态方法是存在于类而不是其实例上的方法/函数。最容易想到的区别是静态方法无法访问 this 并且前面有关键字 static。

    好的,但是如果函数无法访问 this,我们如何调用 this.setState?答案是 — 我们不知道。相反,该函数应该返回更新后的状态数据,如果不需要更新,则返回 null

    返回值与当前 setState 值的行为类似 — 您只需返回状态发生变化的部分,所有其他值将被保留。

    您仍然需要声明组件的初始状态(在构造函数中或作为类字段)。

    getDerivedStateFromProps 在组件的初始挂载和重新渲染时都会调用,因此您可以使用它而不是在构造函数中基于 props 创建状态。

    如果您同时声明 getDerivedStateFromPropscomponentWillReceiveProps,则只会调用 getDerivedStateFromProps,并且您会在控制台中看到警告。

    通常,您会使用回调来确保在实际更新状态时调用某些代码 — 在这种情况下,请改用componentDidUpdate

    【讨论】:

    【解决方案2】:

    使用componentDidUpdate,您可以执行回调和其他取决于正在更新的状态的代码。

    getDerivedStateFromProps 是一个静态函数,因此无法访问 this 关键字。此外,您不会在此处放置任何回调,因为这不是基于实例的生命周期方法。此外,从此处触发状态更改可能会导致循环(例如,使用 redux 调用)。

    它们都有不同的基本目的。如果有帮助,getDerivedStateFromProps 将替换 componentWillReceiveProps

    【讨论】:

    • 那么我的问题是,为什么甚至需要 componentWillReceiveProps 你可以用 componentDidUpdate 做你想做的事情吗?
    • 那么你将如何根据更新的道具更新状态?你需要一种方法来响应道具的变化。
    • 道具可以是状态,在构造函数中,我已经使道具成为状态。 constructor(props){ super(props) this.state = {mystate: props.mystate} }
    • 是的,但是构造函数只被调用一次。更新道具后会发生什么?
    • https://medium.com/@baphemot/whats-new-in-react-16-3-d2c9b7b6193b 这是接受答案的文章,它更深入。
    【解决方案3】:

    getDerivedStateFromProps 基本上可以为您节省一个渲染周期。假设由于某些道具更改,您必须更新某些状态,并且 UI 会以新状态响应。如果没有 getDerivedStateFromProps,你必须等到 componentDidUpdate 被调用来进行 prop 比较并调用 setState 来更新 UI。之后再次调用componentDidUpdate,注意避免无休止的渲染。使用 getDerivedStateFromProps,UI 更新会更早发生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多