【发布时间】:2021-05-02 11:26:32
【问题描述】:
我正在尝试使用 forEach 循环将多个对象添加到状态数组:
const App = () => {
const [pokemon, setPokemon] = useState([]);
axios.get('https://pokeapi.co/api/v2/pokemon') // Gives me 20 pokemon
.then(res => {
res.data.results.map(p => p.url).forEach(url => { // Loops over endpoints of pokemon
axios.get(url)
.then(response => {
setPokemon(response.data)
})
});
})
}
您可能已经猜到了,当我 console.log pokemon 时,只显示 forEach 循环中的最后一项,因为它是最后一个要设置为状态的项。
我正在使用的 api:https://pokeapi.co/。
我首先调用https://pokeapi.co/api/v2/pokemon,它给了我 20 个 pokemon,每个 pokemon 对象都带有一个端点以获取有关它的更多信息,我想将这些端点的信息存储为状态中的对象。
感谢您的帮助,如果您知道更好的方法,请随时告诉我。
【问题讨论】:
标签: javascript reactjs api axios