【发布时间】:2018-08-09 19:40:41
【问题描述】:
我正在使用“fetch”,一切正常。我从 API 获得了一个 json 文件,然后我将结果传递给 setState 中的对象,如下所示:
fetch(
`https://api.io/api/v1/`, {
method:'GET',
headers: {
'content-type': 'application/json',
'x-access-token': 'xxx-xxx-xxx',
}
})
.then(res => res.json())
.then(json => {
this.setState({
index: res.json.result.uv,
isLoading: false,
});
});
现在我需要处理来自 API 的不同结果,在 setState 中为每个对象设置新对象。我发现“Promisse.all”能够仅在一个承诺中为我的不同请求创建一个数组。不幸的是,我没有成功尝试获取这些 json 文件。代码是这样的:
Promise.all([
fetch(
`https://api.io/api/v1/dt=${date1}`, {
method:'GET',
headers: {
'content-type': 'application/json',
'x-access-token': 'xxx-xxx-xxx',
}
}),
fetch(
`https://api.io/api/v1/dt=${date2}`, {
method:'GET',
headers: {
'content-type': 'application/json',
'x-access-token': 'xxx-xxx-xxx',
}
}),
fetch(
`https://api.io/api/v1/dt=${date3}`, {
method:'GET',
headers: {
'content-type': 'application/json',
'x-access-token': 'xxx-xxx-xxx',
}
})
.then(res => res.json())
.then(json => {
this.setState({
index: res[0].json.data,
index1: res[1].json.data,
index2: res[2].json.data,
isLoading: false,
});
});
实际上我可以从数组中得到一个 json 文件:
.then(res => res[0].json())
.then(json => {
this.setState({
index: json.data,
isLoading: false,
});
});
但我在 setState 中需要多个对象(如上),所以它不适用于我的项目:
感谢大家的帮助!!!
【问题讨论】:
-
您是否尝试将 .then(res => res.json()) 添加到您的 promise.all 数组中的每个 fetch 中?不确定这是否可行。
-
.then(responses => Promise.all(responses.map(res => res.json()))) -
@BryanEuton 我还没有尝试过,但它有效!!!!!!!谢啦!!现在我只需要让它更短哈哈
标签: javascript reactjs react-native fetch es6-promise