the*_*uls 3 reactjs recompose higher-order-components react-lifecycle
最近有消息称 React 很快就会被弃用componentWillReceiveProps,取而代之的是新的静态函数getDerivedStateFromProps。在这里查看更多内容
getDerivedStateFromProps我目前正在将我的应用程序迁移到这个新的 API,但由于我正在将重构库用于更高阶的组件,所以我遇到了问题。componentWillReceive我们通过库的生命周期对象来使用props。
所以在转向新的 API 之前,我有以下内容:
export function someHoC () {
return compose(
lifecycle({
componentWillReceiveProps (nextProps) {
const { fetch } = nextProps
if (shouldFetch(this.props, nextProps)) {
fetch()
}
}
})
)
}
Run Code Online (Sandbox Code Playgroud)
现在已更改为以下内容:
export function someHoC () {
return compose(
lifecycle({
getDerivedStateFromProps (nextProps) {
const { fetch } = nextProps
if (shouldFetch(this.props, nextProps)) {
fetch()
}
}
})
)
}
Run Code Online (Sandbox Code Playgroud)
但是,getDerivedStateFromProps需要是静态的,所以我收到了有关此问题的警告,并且不知道如何处理它。
warning.js?7f205b4:33 警告:lifecycle(MyComponent):getDerivedStateFromProps() 被定义为实例方法,将被忽略。相反,将其声明为静态方法。
我该怎么做才能将它作为静态生命周期方法传递到我的组件中?
如果你想使用getDerivedStateFromProps你需要将其声明为静态方法:
static getDerivedStateFromProps() {...}
Run Code Online (Sandbox Code Playgroud)
显然,这使得getDerivedStateFromProps静态,这意味着你不能像调用 一样调用它componentWillReceiveProps。
如果静态方法不适合您,您可以将逻辑移至componentDidUpdate静默警告。setState()但是,如果您从此方法调用,这可能会导致额外的渲染。根据您解决问题时发生的情况fetch(),这可能对您有用。
您也可以替换componentWillReceiveProps为UNSAFE_componentWillReceiveProps( docs ),其工作方式相同。然而,由于即将推出的异步渲染功能,这可能会导致一些问题。
| 归档时间: |
|
| 查看次数: |
8313 次 |
| 最近记录: |