我正在尝试使用Promise.all()
方法在React中获取多个URL:
const urls = [
"https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=2",
"https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=3",
"https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=4"
];
Promise.all(urls.map(url => fetch(url).then(res => res.json()))).then(
members => {
console.log(members);
this.setState({
nearbymems: members.members
});
}
);
console.log将所有URL一起返回,但未在我的地图应用程序中显示它们。
我在状态下声明了一个空数组:nearbymems: []
我还将发布我的render()函数,用于在传单中将数据显示为标记:
{this.state.nearbymems.map(members => (
<Marker
position={[members.location.latitude, members.location.longitude]}
icon={myIcon1}
>
<Popup>
<h1 className="lead">{members.name} </h1>
<PopupModal initialModalState={true} />
</Popup>
</Marker>
))}
谢谢。
编辑:
数组的输出:
(3) [{…}, {…}, {…}]
0:
format:"json"
latlon:"53,-6"
members: Array(50)
0:
bio:" "
date:""
id:44967
location:
{latitude: "53.31138992", longitude: "-6.24345493"}
name: "______"
url:"https://thesession.org/members/___"
__proto__: Object
答案 0 :(得分:1)
您想从每个members
响应中获取fetch
数组,然后将这些数组连接成一个数组,然后再将其置为nearbymems
状态。
Promise.all(
urls.map(url =>
fetch(url)
.then(res => res.json())
.then(res => res.members)
)
).then(members => {
this.setState({
nearbymems: [].concat(...members)
});
});
答案 1 :(得分:1)
Promise.all
返回一个数组,其中每个项目都包含其各自promise的解析值。因此,您不能简单地从members
的结果访问Promise.all
。相反,您必须将所有值合并在一起,以获得每个诺言的members
值的大数组。
这会将每个请求中的所有成员返回到一个扁平数组中。
const urls = [
"https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=2",
"https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=3",
"https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=4"
];
const requests = urls.map(url => fetch(url).then(res => res.json()));
const toMembers = responses => responses.map(response => response.members);
Promise.all(requests).then(toMembers).then(members => console.log(members.flat()));