reactjs - 如何在反应原生应用程序中替换 componentWillReceiveProps?
问题描述
我听说 componentWillRecieveProps 生命周期方法不是在 react native 项目中使用的好选择,而是使用 getDerivedStateFromProps。所以我尝试用 getDerivedStateFromProps 替换我的 componentWillRecieveProps。但我不知道该怎么做,我尝试使用 componentDidUpdate() 但它反复调用 setstate。
componentWillReceiveProps(nextProps) {
if(nextProps.shopList.isFetching===false) {
this.setState({isLoading:false})
if(!_.isEqual(nextProps.shopList, this.props.shopList) && nextProps.shopList.error===false ) {
this.formatShops(nextProps.shopList.shops)
} else {
}
} else {
this.setState({isLoading:true})
}
if(nextProps.common.isFetching===false) {
this.setState({isLoading:false})
if(nextProps.common.error===false) {
if(!_.isEqual(nextProps.common, this.props.common) && nextProps.common.error===false ) {
if(nextProps.common.otpverifysucess==false) {
this.props.navigation.dispatch(logoutAction);
}
}
}
}
}
这是我的整个组件WillRecieveProps。任何人都可以帮助将其移至 getDerivedStateFromProps 生命周期方法
解决方案
想法是,将所有状态更新部分放在getDerivedStateFromProps
方法中,并将所有基于新道具和旧道具值之间差异的动作放在componentDidUpdate
方法中。componentDidUpdate
将获取 prevProps 值作为参数,this.props
并将具有新的 props 值。
要替换componentWillReceiveProps
by componentDidUpdate
:
因此,如果您要替换componentWillReceiveProps
,请componentDidUpdate
替换nextProps
为this.props
和this.props
。prevProps
nextProps
(componentWillReceiveProps 的参数) 到this.props
(incomponentDidUpdate
)
this.props
(在 componentDidUpdate 内) 到prevProps
(incomponentDidUpdate
)
试试这个代码:
getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.shopList.isFetching === false || nextProps.common.isFetching === false) {
return { isLoading: false }
} else {
return { isLoading: true }
}
}
componentDidUpdate(prevProps) {
if(this.props.shopList.isFetching === false) {
if(!_.isEqual(this.props.shopList, prevProps.shopList) && this.props.shopList.error === false ) {
this.formatShops(this.props.shopList.shops)
}
}
if(this.props.common.error === false && this.props.common.isFetching === false) {
if(!_.isEqual(this.props.common, prevProps.common) && this.props.common.error === false) {
if(this.props.common.otpverifysucess == false) {
this.props.navigation.dispatch(logoutAction);
}
}
}
}
推荐阅读
- sql - 如何加入两个不同的选择语句以返回任何匹配的结果?
- reactjs - 如何创建一个忽略回调参数的固定单个参数的函数
- c# - 输入数据时希望文本框清空
- r - 数据框之间的条件搜索、匹配、过滤和替换值
- vb.net - vb.net 托管内存和堆稳定但进程内存使用导致崩溃
- gcc - GCC libc 版本
- apache - Ant - 宏定义中 concat 目标中的字符串重复 - 为什么
- sql-server - 如何使用触发器更新 SQL Server 中的列
- c# - 返回线上的 Parasoft 违规 EXCEPT.NCSAE-3
- windows - 我可以将 Google Assistant 消息发送到我的 Windows 应用程序,但如何发回消息?