我发出了两个api GET请求,对于这两个请求,我希望更新状态。由于某些原因,它仅使用第一个GET请求中的值进行更新。
我已经尝试使用扩展操作符来更新状态,并从GET请求中向当前状态(类别)添加新值。
axios // first get request
.get(
"LINK_TO_API"
)
.then(res => {
this.setState({
...this.state.categories,
categories: res.data.data
});
})
.catch(function(error) {
console.log(error);
});
axios // second get request
.get(
"LINK_TO_API"
)
.then(res => {
this.setState({
...this.state.categories,
categories: res.data.data
});
})
.catch(function(error) {
console.log(error);
});
我目前从第一个GET请求中获得10个值,并希望在通过类别映射时获得20个值的总和。
发布于 2019-04-22 16:22:14
你永远不会得到20个值,因为没有附加值,你只是在每次调用中覆盖类别值。
this.setState({
...this.state.categories,
categories: res.data.data
});
在这里,categories: res.data.data
被覆盖了。
只需将代码修改为:
axios
.get(
"LINK_TO_API"
)
.then(res => {
this.setState((state) => ({
...state,
categories: [...state.categories, ...res.data.data]
}));
})
.catch(function(error) {
console.log(error);
});
发布于 2019-04-22 16:20:27
假设categories是一个array
,您将用另一个数组覆盖另一个数组。
在下面的代码中,我总是返回一个新的数组,并将新的数组与以前的数组连接起来。
axios // first get request
.get('LINK_TO_API')
.then(res => {
this.setState({
categories: [...this.state.categories, ...res.data.data]
});
})
.catch(function(error) {
console.log(error);
});
axios // second get request
.get('LINK_TO_API')
.then(res => {
this.setState({
categories: [...this.state.categories, ...res.data.data]
});
})
.catch(function(error) {
console.log(error);
});
发布于 2019-04-22 16:24:25
首先,您的扩散操作符是错误的,您必须将其包装到数组categories: [...this.state.categories, ...res.data.data]
中。另外,我建议你等待你所有的帖子加载,然后将它们设置为状态:
Promise.all([axios.get('LINK_TO_API'), axios.get('LINK_TO_API_2')])
.then(allYourPosts => {
this.setState({ /* set it to state */ });
})
.catch((error) => {
console.log(error);
});
https://stackoverflow.com/questions/55791211
复制相似问题