简体   繁体   English

如何在 React 数组映射中显示从 API 获取的数据

[英]How to show data fetched from API inside React array map

I am trying to map an array of objects inside a React functional component.我正在尝试在 React 功能组件内映射一组对象。 Here is a part of my object:这是我的对象的一部分:

[{"id":1,"name":"Cordoba Park","start_date":"2020-03-19","address":null,"region":1,"country":2}] 

My problem is how to map this object into a table and fetch from the API the region and country by Id at the same time.我的问题是如何将此对象映射到表中,并同时通过 Id 从 API 中获取地区和国家/地区。 I am using Redux hooks to fetch data from my API.我正在使用 Redux 钩子从我的 API 中获取数据。

<tbody>
  {
    hotels.payload.map((hotel) => (
        <tr key={hotel.id}>
            <td>
                <div className="d-flex flex-column">
                    <h5>{hotel.name}</h5>
                    <p className="text-muted">{hotel.chain}</p>
                </div>
            </td>
            <td>{hotel.country}</td>
            <td>{hotel.region}</td>
            <td>
                <Badge className="p-2" variant={hotel.active ? 'success' : 'danger'}>
                    {hotel.active ? 'Activo' : 'Inactivo'}
                </Badge>
            </td>
            <td>
                <Button className="mx-1" variant="light">
                    <i className="fas fa-edit" />
                </Button>
                <Button className="mx-1" variant="light">
                    <i className="fas fa-trash" />
                </Button>
            </td>
        </tr>
    ));
 }
</tbody>

It's not a good idea to make an API call inside the render function.在渲染函数内进行 API 调用并不是一个好主意。 It's called each time any prop is updated and therefore you'll have too many api calls and a very bad performance.每次更新任何道具时都会调用它,因此您将有太多的 api 调用和非常糟糕的性能。

You should reorganize your code to load the data first and then render the results您应该重新组织代码以先加载数据,然后再呈现结果

Ideally, I would try to get the data from the source in the first API call but I assume that it's not possible...理想情况下,我会尝试在第一个 API 调用中从源获取数据,但我认为这是不可能的......

If not, in the redux action you should query for the hotel results one by one and update the store only once.如果没有,则在 redux 操作中,您应该一一查询酒店结果,并且仅更新商店一次。

You can have a look at the axios library to make your call您可以查看 axios 库来拨打电话

There is a nice Axios.all() utility that lets you make all the API calls and wait for all results before calling the callback function.有一个很好的 Axios.all() 实用程序,它允许您进行所有 API 调用并在调用回调函数之前等待所有结果。 Axios All example Axios 全部示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM