在React中使用fetch加载多个URL

时间:2019-03-12 09:40:28

标签: reactjs leaflet

我正在尝试使用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

2 个答案:

答案 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()));