如何在重构库中使用 HoC 创建 React 的新静态函数 getDerivedStateFromProps 作为生命周



最近有消息称,很快 React 将弃用componentWillReceiveProps,取而代之的是新的静态函数getDerivedStateFromProps。在此处查看更多内容

目前正在将我的应用程序迁移到这个新的 API,但由于我正在将重构库用于更高阶的组件,因此在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(( 被定义为实例方法,将被忽略。而是将其声明为静态方法。

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

如果要使用getDerivedStateFromProps则需要将其声明为静态方法:

static getDerivedStateFromProps() {...}

显然,这使得getDerivedStateFromProps静态的,这意味着您不能像调用componentWillReceiveProps一样调用它。

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

您还可以将componentWillReceiveProps替换为UNSAFE_componentWillReceiveProps(文档(,其工作方式相同。但是,由于即将推出的异步渲染功能,这可能会导致一些问题。

您应该在生命周期中使用以下方法

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

最新更新