简体   繁体   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. 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 - I have console.log(posts) but it does not seem any of the objects are being saved into the state. https://codesandbox.io/s/multiple-get-requests-gerjq - 我有 console.log(posts) 但似乎没有任何对象被保存到 state 中。

Any idea where I am going wrong?知道我哪里出错了吗?

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

You need to access the three responses as three arguments to axios.spread and return the mapped result您需要访问三个响应作为三个 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}`
        })
      );
    })
  )

Working demo工作演示

I would recommend instead of normal setState, try using setState with callback function.我建议不要使用普通的 setState,而是尝试使用带有回调 function 的 setState。 Just replace your setState code with the code below:只需将您的 setState 代码替换为以下代码:

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

Instead of console.log, you can use any function as well.除了 console.log,您也可以使用任何 function。 But your state will be updated for sure.但是您的 state 肯定会更新。

for axios multi request please follow this pattern对于 axios 多请求,请遵循此模式

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

you need to store your api data to your state in order to available the request data inside your component.您需要将 api 数据存储到 state 以便在组件中使用请求数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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