简体   繁体   中英

React: how to prevent api calls in ComponentDidMount and in ComponentDidUpdate override each other

In componentDidMount I am fetching data using a Redux action, for example:

componentDidMount() {
   let parameter = some code;
   this.props.getAction(parameter).then(r => {
     if(r.type.endsWith('SUCCESS')){
       this.setState({cList: r.payload.data.data})
     }
   }
}

and then, in the componentDidUpdate I need to fetch again data, when the parameters inside the function change (I am using lodash ):

componentDidUpdate(prevProps, prevState){
   if(!isEqual(this.props.parameter, prevProps.parameter){
     let parameter = some code;
     if(r.type.endsWith('SUCCESS')){
       this.setState({cList: r.payload.data.data})
     }
   }
}

The problem is that if the Promise in the componentDidUpdate returns the result before the Promise in componentDidMount , when I have my parameter changed in the component, the data shown is wrong; it is still showing the data from componentDidMount and not from the new action calls in the componentDidUpdate .

I hope everything is clear.

How can I avoid this? Thanks.

You can keep an instance variable lastRequestId in your component to track which promise is running, something like this :

class MyComponent extends Component {
  constructor(props) {
    super(props);

    this.lastRequestId = null;
  }

  componentDidMount() {
    let parameter = "some code";
    this.lastRequestId = 'ON_MOUNT_REQUEST';
    this.props.getAction(parameter).then(r => {
      if(r.type.endsWith('SUCCESS') && this.lastRequestId === 'ON_MOUNT_REQUEST'){
        this.setState({cList: r.payload.data.data})
      }
    })
  } 

  componentDidUpdate(prevProps, prevState){
    if(!isEqual(this.props.parameter, prevProps.parameter)) {
      let parameter = "some code";
      this.lastRequestId = 'ON_UPDATE_REQUEST';
      this.props.getAction(parameter).then(r => {
        if(r.type.endsWith('SUCCESS') && this.lastRequestId === 'ON_UPDATE_REQUEST'){
          this.setState({cList: r.payload.data.data})
        }
      })
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM