javascript - shouldComponentUpdate 中的变异状态反应 16.6.3
问题描述
由于 react 已弃用其中的许多内容,因此Lifecycle Methods
我发现,在使用时redux
以及connect
当我想增加component
我正在使用的 a 的本地状态时componentDidUpdate
。问题只是prevProps, prevState
传递给这个函数。
那意味着我只有nextProps, nextState
在shouldComponentUpdate
lifeCycle` 里面。
对我来说,做如下事情本质上是错误的:
shouldComponentUpdate(nextProps) {
const { status_status } = nextProps;
if(status_status === "error") {
this.props.dispatch(resetStatus());
}
return true;
}
这肯定是一个antiPattern
,我不应该这样做。
那么我怎样才能在nextProps
不使用的情况下获得shouldComponentUpdate
解决方案
我遇到了类似的情况,我发现 getDerivedStateFromProps 在这种情况下很有用且合适。
static getDerivedStateFromProps(props, state) {
// now, you may dispatch checking the condition
// BTW, you will dispatch just using props
// props.dispatch()
// this.props.dispatch() // invalid
}
我从文档中知道这个注释:
如果您需要执行副作用(例如,数据获取或动画)以响应道具的变化,请改用 componentDidUpdate 生命周期。
但我只是分享我的经验,这只是案例getDerivedStateFromProps
。
但是,我也建议您先使用componentDidUpdate
钩子。如果一切看起来对你都很好,那就坚持下去。或者,如果您也面临使用componentDidUpdate
并感觉很好,getDerivedStateFromProps
那么您可以发表您的意见和想法作为答案。
推荐阅读
- javascript - 使用 URI 和密钥生成 HMAC SHA 算法
- java - 无法匹配或比较两个日期
- algorithm - 从给定的组列表中形成一个新组,该组满足两个整数 k1 和 k2 之间的总分。
- python - 要列出的 Python 文本文件
- php - 如何在 PHP 中对多项式进行计算?
- active-directory - .Net Core 2 WebApi 到使用 Active Directory 的 SQL Server
- php - 图像未在 codeigniter 中显示
- sparql - 如何将 SPARQL 查询翻译成英文
- sql - T-SQL 较差的 CTE 连接性能
- r - 有条件地将CircleMarkers 添加到传单