javascript - axios获取多个JSON端点并保存到状态(react)

标签 javascript reactjs axios

我正在尝试将 axios get 请求从 1 个 JSON 端点更新为 3 个 JSON 端点,然后将帖子保存到组件状态中。

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

知道我哪里出错了吗?

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

最佳答案

您需要将三个响应作为 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

关于javascript - axios获取多个JSON端点并保存到状态(react),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58394592/

相关文章:

javascript - 重定向没有任何引用网址的网址

javascript - 无法访问用作路由中元素的组件中的子组件(react-router-dom 6.3.0)

javascript - NodeJs 在外部数据请求时内存不足

javascript - Titanium HealthKit 模块 - 无法创建按来源累积和分隔的统计查询

javascript - 显示 Javascript 函数的结果

javascript - 如何在 this.state 中使用 this.state

reactjs - 从字符串 : ReactJS 动态渲染组件

javascript - 无法读取属性对象 reactJS

javascript - 如何使用 FastAPI 为跨源请求设置 cookie

javascript - jQuery 在嵌套 divd 中选择 href 值