Axios获得多个JSON端点并保存到状态(反应)

问题描述 投票:0回答:1

我正在尝试将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 }));
}
javascript reactjs axios
1个回答
0
投票

对于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数据存储到您的状态,以便在组件内部提供请求数据。


0
投票

您的Axios.spread参数检索格式不正确,您必须按如下方式使用第二个参数:

 axios.spread((acct, response) => // use 2nd parameter
          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}`,
            url: `${post.AbsoluteUrl || post.adUrl.localization[0].value}`
          }))
        )
© www.soinside.com 2019 - 2024. All rights reserved.