我正在尝试将 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}`
})
);
})
)
关于javascript - axios获取多个JSON端点并保存到状态(react),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58394592/