我听说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
的componentDidUpdate
:
所以,如果您要更换componentWillReceiveProps
用componentDidUpdate
,更换nextProps
用this.props
和this.props
用prevProps
。
nextProps
(componentWillReceiveProps的参数)为this.props
(中的componentDidUpdate
)
this.props
(在componentDidUpdate内部)到prevProps
(在中componentDidUpdate
)
试试这个代码:
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);
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句