簡體   English   中英

在componentDidMount內部處理多個axios獲取請求

[英]Handling multiple axios get requests inside componentDidMount

我有一個像這樣的React組件:

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

     this.state = {
       name: '',
       address: '',
       phone: ''
     }
   }

   componentDidMount() {
     //APIcall1 to get name and set the state
     //i.e., axios.get().then(this.setState())
     //APIcall2 to get address and set the state
     //APIcall3 to get phone and set the state
    }
 }`

如您所見,我正在發出三個API獲取請求以獲取詳細信息,並在獲取數據后三次設置狀態。 因此,我收到此錯誤:

警告:在現有狀態轉換期間(例如在render或其他組件的構造函數中)無法更新。 渲染方法應該純粹是道具和狀態的函數; 構造函數的副作用是反模式,但是可以將其移至componentWillMount

順便說一句,我沒有在render方法中引起狀態改變。 無論如何要解決這個問題?

由於axios.get返回一個axios.get ,您可以在調用setState之前將它們鏈接在一起。 例如,使用Promise.all

componentDidMount() {
  Promise.all([
    APIcall1, // i.e. axios.get(something)
    APIcall2,
    APIcall3
  ]).then(([result1, result2, result3]) => {
    // call setState here
  })
}

請注意,如果任何api調用失敗,Promise.all將捕獲,並且不會調用setState。

在axios中,您可以使用axios.all方法:

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

或者,您可以使用標准的Promise.all

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
  .then(data => {
    // Both requests are now complete
  });

暫無
暫無

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

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