首页 > 解决方案 > 如何在反应原生应用程序中替换 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 生命周期方法

标签: reactjsreact-native

解决方案


想法是,将所有状态更新部分放在getDerivedStateFromProps方法中,并将所有基于新道具和旧道具值之间差异的动作放在componentDidUpdate方法中。componentDidUpdate将获取 prevProps 值作为参数,this.props并将具有新的 props 值。

要替换componentWillReceivePropsby componentDidUpdate

因此,如果您要替换componentWillReceiveProps,请componentDidUpdate替换nextPropsthis.propsthis.propsprevProps

nextProps(componentWillReceiveProps 的参数) 到this.props(in componentDidUpdate)

this.props(在 componentDidUpdate 内) 到prevProps(in 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);
      }
    }
  }
}

推荐阅读