首页 > 解决方案 > getDerivedStateFromProps() 与 componentDidUpdate()

问题描述

componentWillReceiveProps在我的应用程序中的很多地方都在使用它。现在,我必须用getDerivedStateFromProps()or替换它们componentDidUpdate()。首先,我想使用getDerivedStateFromPropsas it s 替代componentWillReceivePropsasSuggested react-nativedocs。但是有些人强烈建议不要使用这种方法,而是建议使用componentDidUpdate. 但是对于我的要求,所有新道具都必须使用state之前的渲染进行设置。getDerivedStateFromProps是最好的地方。

因此,在getDerivedStateFromProps和之间使用哪一个componentDidUpdate

标签: react-nativegetderivedstatefromprops

解决方案


来自 React 文档

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

getDerivedStateFromProps在调用 render 方法之前调用,无论是在初始挂载时还是在后续更新时。它应该返回一个对象来更新状态,或者返回 null 来更新任何内容。

派生状态会导致冗长的代码并使您的组件难以思考。

确保您熟悉更简单的替代方案:

  • 如果您需要执行副作用(例如,数据获取或动画)以响应道具的变化,请改用componentDidUpdate生命周期。
  • 如果您只想在 prop 更改时重新计算某些数据,请改用 memoization helper。
  • 如果您想在 prop 更改时“重置”某些状态,请考虑使用键使组件完全受控或完全不受控。

推荐阅读