我正在尝试将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多请求,请遵循此模式
axios.all([
axios.get('http://google.com'),
axios.get('http://apple.com')
]).then(axios.spread((googleRes, appleRes) => {
this.setState({google: googleRes, apple: appleRes});
});
您需要将api数据存储到您的状态,以便在组件内部提供请求数据。
您的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}`
}))
)