Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何创建React';s的新静态函数getDerivedStateFromProps作为生命周期方法,使用重组库中的HoC?_Reactjs_Higher Order Components_Recompose_React Lifecycle - Fatal编程技术网

Reactjs 如何创建React';s的新静态函数getDerivedStateFromProps作为生命周期方法,使用重组库中的HoC?

Reactjs 如何创建React';s的新静态函数getDerivedStateFromProps作为生命周期方法,使用重组库中的HoC?,reactjs,higher-order-components,recompose,react-lifecycle,Reactjs,Higher Order Components,Recompose,React Lifecycle,最近,有消息称,soon React将不推荐使用组件willreceiveProps,取而代之的是新的静态函数getDerivedStateFromProps 我目前正在将我的应用程序迁移到此新API,但由于我使用的是高阶组件的重新组合库,因此我的getDerivedStateFromProps出现了问题。我们使用组件将通过库的生命周期对象接收道具 因此,在使用新API之前,我有以下几点: export function someHoC () { return compose( li

最近,有消息称,soon React将不推荐使用
组件willreceiveProps
,取而代之的是新的静态函数
getDerivedStateFromProps

我目前正在将我的应用程序迁移到此新API,但由于我使用的是高阶组件的重新组合库,因此我的getDerivedStateFromProps出现了问题。我们使用
组件将通过库的生命周期对象接收
道具

因此,在使用新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()被定义为实例方法,将被忽略。相反,将其声明为静态方法


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

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


setStatic('getDerivedStateFromProps',(nextProps,prevState)=>{})
并将以前的值存储在组件状态中,以便从
prevState
参数中检索它。如果要使用
getDerivedStateFromProps
,则需要将其声明为:

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

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


您还可以将
组件WillReceiveProps
替换为
不安全组件WillReceiveProps
(),其工作方式相同。但是,由于即将到来的异步渲染特性,.< /p>告诉我你的DO填充会更新OP,但是它与问题无关,这就是为什么我选择删除它。你可以使用<代码> SETSTATION/CODE >,但这实际上会修改基本组件,这可能不是你想要的。但它并没有解决我的问题,正因为如此。在生命周期之外。
static getDerivedStateFromProps() {...}