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

时间:2019-10-15 12:22:23

标签: 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 }));
}

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

我建议您使用正常的setState和回调函数,而不是通常的setState。 只需将您的setState代码替换为以下代码:

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

您也可以使用任何功能来代替console.log。但是您的状态肯定会更新。

答案 2 :(得分: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数据存储到您的状态,以便在组件内部使用请求数据。