如何在React中并行渲染列表

huangapple go评论61阅读模式
英文:

How to render list in parallel in react

问题

例如,如果我在 ItemList 组件中有一些 ID 列表:

{itemIds.map((itemId, index) => { return <Item key={itemId} itemId={itemId} />; })}

然后在 Item 组件内部,我根据每个项目的 ID 进行 API 请求。

如何以最佳方式并行运行这些 ID 请求?我真的需要使用 Promise.all()Promise.allSettled() 吗?有没有其他替代方法?

英文:

For example if I have some list of IDs in ItemList component:

{itemIds.map((itemId, index) =&gt; { return &lt;Item key={itemId} itemId={itemId} /&gt;; })}

and then inside Item component I make API request for each of the items by their ID.

How do I make these ID requests to run in parallel in the best possible way? Do I really have to use Promise.all() or Promise.allSettled()? Any alternatives to that?

答案1

得分: 1

这取决于您的需求。如果您需要将所有数据一起解决,您需要使用 Promise.allPromise.allSettled,如果您想要显示每个已解决的项目,可以从每个项目发送请求。

但从后端的角度来看,以这种方式调用数据的任何方法都将导致向服务器发送大量请求,特别是如果有很多项目。

更好的方法是创建一个API,将ID发送到服务器,并在前端通过循环遍历这些项目,一次性返回所有这些项目。

英文:

It depends, if you need all you data to resolved together you need to use Promise.all or Promise.allSettled, if you want to show whatever item resolved you can send the request from each item.

But from the backend perspective, whatever method you use to call the data this way will lead to a lot of requests to the server, especially if there are a lot of items.

It would be better to make an API to send the IDS and return all these items together in one request and from the front end, you loop through the items.

答案2

得分: 1

另一种方法是在for循环中使用async/await,就像这个示例:

async function getItems(itemIds) {
  const items = [];
  for (const itemId of itemIds) {
    const response = await fetch(`https://example.com/items/${itemId}`);
    const data = await response.json();
    items.push(data);
  }
  return items;
}

getItems(itemIds)
  .then(items => {
    // 处理项目数据数组
  })
  .catch(error => {
    // 处理任何错误
  });
英文:

An alternative would be to use async/await in a for loop, like this example :

async function getItems(itemIds) {
  const items = [];
  for (const itemId of itemIds) {
    const response = await fetch(`https://example.com/items/${itemId}`);
    const data = await response.json();
    items.push(data);
  }
  return items;
}

getItems(itemIds)
  .then(items =&gt; {
    // Handle the array of item data
  })
  .catch(error =&gt; {
    // Handle any errors
  });

huangapple
  • 本文由 发表于 2023年2月27日 18:05:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定