我正在try 使用Reaction显示从API获取的数据.
我正在从https://pokeapi.co/docs/v2获取数据,我打算显示返回的名称和URL,并操作它们来练习条件渲染等
但我似乎陷入了一个无限循环.
我已经在谷歌上搜索过了,它建议我使用React.useEffect()
,但即使我这样做了,我仍然会得到错误:
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
个
我的代码如下:
App.js
import React from 'react'
import PokemonList from "./PokemonList";
function App() {
const [pokemons, setPokemons] = React.useState([]);
React.useEffect(() => {
console.log('fetch ran')
fetch('https://pokeapi.co/api/v2/pokemon').then(res => res.json())
.then(data => {
setPokemons(() => data);
})
}, [])
return (
<div>
<PokemonList pokemons={pokemons} />
</div>
)
}
export default App;
PockemonList.js :
import React from 'react'
export default function PokemonList({ pokemons }) {
const [pokemonsArray, setPokemonsArray] = React.useState([]);
setPokemonsArray(()=>pokemons.results)
const pokemonsElements = pokemonsArray.map((pokemon) => {
return (
<div key={pokemon.name}>
<h3>{pokemon.name}</h3>
<p>{pokemon.url}</p>
<hr />
</div>
)
})
return (
<div>
{pokemonsElements}
</div>
)
}
有时我也会收到这样的错误:
Consider adding an error boundary to your tree to customize error handling behavior.
.
react-refresh-runtime.development.js:315 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
.
我假设这是BC,当数据尚未返回时,我会try 运行.map().
有谁可以帮我?如果这是一个愚蠢的问题,我很抱歉,但我已经被困了这么长时间,找不到答案.这样做的正确方法是什么?