【问题标题】:How to create React's new static function getDerivedStateFromProps as a lifecycle method using an HoC in the recompose library?如何使用 recompose 库中的 HoC 创建 React 的新静态函数 getDerivedStateFromProps 作为生命周期方法?
【发布时间】:2018-09-27 19:53:20
【问题描述】:

最近有消息称,React 很快就会弃用 componentWillReceiveProps,取而代之的是新的静态函数 getDerivedStateFromPropsSee more here

我目前正在将我的应用程序迁移到这个新的 API,但是由于我正在使用 recompose 库来处理更高阶的组件,所以我遇到了getDerivedStateFromProps 的问题。我们通过库的生命周期对象使用componentWillReceive 属性。

所以在迁移到新的 API 之前,我有这个:

export function someHoC () {
  return compose(
    lifecycle({
      componentWillReceiveProps (nextProps) {
        const { fetch } = nextProps
          if (shouldFetch(this.props, nextProps)) {
             fetch()
          }
      }
    })
  )
}

现在已更改为以下内容:

export function someHoC () {
  return compose(
    lifecycle({
      getDerivedStateFromProps (nextProps) {
          const { fetch } = nextProps
          if (shouldFetch(this.props, nextProps)) {
             fetch()
          }
      }
    })
  )
}

但是,getDerivedStateFromProps 必须是静态的,所以我收到了关于此的警告,但不知道如何处理。

warning.js?7f205b4:33 警告:生命周期(MyComponent):getDerivedStateFromProps() 被定义为实例方法,将被忽略。而是将其声明为静态方法。

如何将它作为静态生命周期方法传递到我的组件中?

【问题讨论】:

  • 告诉我你的工作内容
  • 我会更新OP,但它与问题无关,这就是我选择删除它的原因。
  • 您可以使用setStatic,但这实际上会修改基本组件,这可能不是您想要的。
  • 我确实考虑过这一点,但它并不能解决我的问题。

标签: reactjs higher-order-components recompose react-lifecycle


【解决方案1】:

您应该在生命周期中使用以下内容

setStatic('getDerivedStateFromProps', (nextProps, prevState) => {}) 并将以前的值存储在组件状态中,以便从 prevState 参数中检索它

【讨论】:

  • 生命周期之外。
【解决方案2】:

如果你想使用getDerivedStateFromProps,你需要将它声明为static method

static getDerivedStateFromProps() {...}

显然,这会使getDerivedStateFromProps 成为静态,这意味着您不能像调用componentWillReceiveProps 那样称呼它。

如果静态方法对您不起作用,您可以将您的逻辑移动到 componentDidUpdate 以使警告静音。但是,如果您从此方法调用setState(),这可能会导致额外的渲染。根据您解析 fetch() 时发生的情况,这可能对您有用。

您也可以将componentWillReceiveProps 替换为UNSAFE_componentWillReceiveProps (docs),其工作方式相同。但是,由于即将推出的异步渲染功能,this could cause some issues.

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 2017-05-29
    • 1970-01-01
    • 2018-09-12
    • 2020-05-16
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 2017-08-28
    相关资源
    最近更新 更多