簡體   English   中英

反應:這未在異步回調函數中定義

[英]React: this is not defined in async callback function

我已經在這上面很久了,我需要幫助。 我正在嘗試調用 API 鏈接,並且我有一個數據數組可以將調用作為調用的參數。 調用完成后,我想將組件狀態設置為獲得的結果。

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只有在你想一個接一個地執行一個請求時才有意義,然后你必須調用cb()以便鏈繼續:

 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(); // <---
   });
});

或者並行執行所有操作(這可能要快得多):

 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:您應該始終處理承諾中的錯誤,因此只需將.catch(/*..*/)附加到鏈...,

forEach和 api 請求回調使用箭頭函數,這將防止 javascript 在回調鏈中重新分配this的值。

有關 ES6 中箭頭函數的更多信息,請閱讀: https ://codeburst.io/javascript-arrow-functions-for-beginners-926947fc0cdc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM