簡體   English   中英

Axios 獲取多個 JSON 端點並保存到 state (反應)

[英]Axios get multiple JSON end points and save into state (react)

I am trying to update my axios get request from 1 JSON end point to 3 JSON end points and then save the posts into the component state.

https://codesandbox.io/s/multiple-get-requests-gerjq - 我有 console.log(posts) 但似乎沒有任何對象被保存到 state 中。

知道我哪里出錯了嗎?

 private getPosts() {
  axios
    .all([
      axios.get("https://cors-anywhere.herokuapp.com/" + "https://...."),
      axios.get("https://cors-anywhere.herokuapp.com/" + "https://...."),
      axios.get("https://cors-anywhere.herokuapp.com/" + "https://www..."),
      axios.get("https://cors-anywhere.herokuapp.com/" + "http://api...."),
      axios.get("https://cors-anywhere.herokuapp.com/" + "https://www..."),
      axios.get("https://cors-anywhere.herokuapp.com/" + "https://www...")
    ])
    .then(axios.spread((response =>
      response.data.map(post => ({
        id: `${ post.Id || post.jobId }`,
        name: `${ post.Name || post.advertisements[0].title.localization[1].value }`,
        company: `${ post.Company || 'Ohly' }`,
        summary: `${ post.Summary }`
      }))
    )))
    .then(posts => {
      this.setState({
        posts,
        isLoading: false
      });
    })
     // Error catching
    .catch(errors => this.setState({ errors, isLoading: false }));
}

您需要訪問三個響應作為三個 arguments 到 axios.spread 並返回映射結果

.then(
    axios.spread((response, response1, response2) => {
      return [...response.data, ...response1.data, ...response2.data].map(
        post => ({
          id: `${post.Id || post.jobId}`,
          name: `${post.Name ||
            post.advertisements[0].title.localization[1].value}`,
          company: `${post.Company || "Ohly"}`,
          summary: `${post.Summary}`,
          url: `${post.AbsoluteUrl || post.adUrl.localization[0].value}`
        })
      );
    })
  )

工作演示

我建議不要使用普通的 setState,而是嘗試使用帶有回調 function 的 setState。 只需將您的 setState 代碼替換為以下代碼:

this.setState({
      posts,
      isLoading: false
    }, () => {
      console.log(this.state)
    });

除了 console.log,您也可以使用任何 function。 但是您的 state 肯定會更新。

對於 axios 多請求,請遵循此模式

axios.all([
 axios.get('http://google.com'),
 axios.get('http://apple.com')
]).then(axios.spread((googleRes, appleRes) => {
  this.setState({google: googleRes, apple: appleRes});
});

您需要將 api 數據存儲到 state 以便在組件中使用請求數據。

暫無
暫無

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

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