在React中映射时处理多个get请求



我有一个组件,我通过一个数组map()来呈现子组件。

这是我代码的一部分:

// example pokemons
const pokemons = [
{
id: 1  
name: "bulbasaur"
},
{
id: 2,
name: "ivysaur"
},
{
id: 3,
name: "venusaur"
}
];
// map through pokemons
const mappedPokemons = pokemons.map((p, i) => {
return <Pokemon key={i} pokemon={p} />;
});
// render
return (
<div className="ml-3">
<h1 className="text-center mb-5">Pokémons:</h1>
<div className="row">{mappedPokemons}</div>
</div>
);

在子组件中,get请求使用axios从公共API (pokeapi)获取数据。

const [pm, setPm] = useState(null);
useEffect(() => {
axios
.get("https://pokeapi.co/api/v2/pokemon/" + pokemon.id)
.then((response) => {
setPm(response.data);
})
.catch((error) => {
console.log(error);
});
}, [pokemon.id]);

我想要实现的是等到所有数据在渲染组件之前被接收,我听说过Promise.all(),但我不确定在哪里实现它,如果这是正确的方法。

我做了这个沙盒,让你可以尝试一些东西。

如果状态被放到父组件中,你可以很容易地等待所有的解决。将pokemons置于状态,则:

// parent
useEffect(() => {
Promise.all(
pokemons.map(p => axios
.get("https://pokeapi.co/api/v2/pokemon/" + p.id)
.then(res => res.data)
)
)
.then((allData) => {
const combined = pokemons.map((p, i) => ({ ...p, data: allData[i] }));
setPokemons(combined);
})
.catch(handleErrors); // don't forget this
}, []);

然后,只有在pokemons[0].data存在时才渲染子组件,并根据需要使用pokemonprop中的数据。

最新更新