react-native - getDerivedStateFromProps() 与 componentDidUpdate()
问题描述
我componentWillReceiveProps
在我的应用程序中的很多地方都在使用它。现在,我必须用getDerivedStateFromProps()
or替换它们componentDidUpdate()
。首先,我想使用getDerivedStateFromProps
as it s 替代componentWillReceiveProps
asSuggested react-native
docs。但是有些人强烈建议不要使用这种方法,而是建议使用componentDidUpdate
. 但是对于我的要求,所有新道具都必须使用state
之前的渲染进行设置。getDerivedStateFromProps
是最好的地方。
因此,在getDerivedStateFromProps
和之间使用哪一个componentDidUpdate
?
解决方案
来自 React 文档
https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
getDerivedStateFromProps
在调用 render 方法之前调用,无论是在初始挂载时还是在后续更新时。它应该返回一个对象来更新状态,或者返回 null 来更新任何内容。
派生状态会导致冗长的代码并使您的组件难以思考。
确保您熟悉更简单的替代方案:
- 如果您需要执行副作用(例如,数据获取或动画)以响应道具的变化,请改用
componentDidUpdate
生命周期。- 如果您只想在 prop 更改时重新计算某些数据,请改用 memoization helper。
- 如果您想在 prop 更改时“重置”某些状态,请考虑使用键使组件完全受控或完全不受控。
推荐阅读
- javascript - jQuery hide 不隐藏 vb.net/asp.net webform 中的任何内容
- android - 如何根据手机屏幕大小自动调整视图大小
- python - xlwt/xlutils.copy 不保留单元格(我没有触摸)格式
- ios - 只替换字符串中的粗体字,Swift
- angular - 何时在 Angular 中使用模板与组件?
- asp.net - ASP.NET MVC Bootstrap 无法正常工作
- graphql - Shopify GraphQL 查询过滤器上的部分匹配
- java - 线程“主”org.jboss.modules.ModuleLoadError 中的异常:模块系统:在本地模块加载器@6267c3bb 中找不到主
- assets - CMYK 图像显示为底片
- c# - 如何获取 Json 值并将其填充到 ASP.NET 中的数据集上