简体   繁体   中英

React: this is not defined in async callback function

I have been on this for long now please I need assistance. Am trying to make a call to an API link and I have an array of data to make the call as parameters to the call. And After the call has been made I want to set the component state to the result gotten.

let animals = ['cats','goats'] ;
async.each(animals, function(item, cb){
  axios.get(`http://api.com?keyword=${item}`)
    .then(res=> {
        apiData.push(res.data)
        this.setState({
          stateData: apiData 
        });
     });
   })

async.each only makes sense if you want to execute one request after another, and then you have to call cb() so that the chain continues:

 async.each(array, (item, cb) => { // <- arrow func!
   axios.get(`/http://api.com?keyword=${item}`)
   .then(res => {
     apiData.push(res.data);
     this.setState({ stateData: apiData });
     cb(); // <---
   });
});

Or to execute all in parallel (which is probably much faster):

 const promises = array.map(item => axios.get(`/http://api.com?keyword=${item}`).then(res => res.data));

 Promise.all(promises).then(stateData => {
   this.setState({ stateData });
 });

PS: You should always handle errors in a promise, so just attach a .catch(/*..*/) to the chain ...,

Use arrow function for both forEach and api request callback, that will prevent javascript re-assigning the value of this during your callback chain.

More info about arrow functions in ES6 read: https://codeburst.io/javascript-arrow-functions-for-beginners-926947fc0cdc

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