React:TypeError:无法读取未定义的属性(读取‘map’)
2021-10-13
293
我是 React 的新手。我通过 API 获取 pokemon。基本上,当我单击其中一个 pokemon 时,我想了解该 pokemon 的详细信息。但是,我在标题中收到此错误。我知道我的 PokemonDetail.js 文件中存在问题。但是我无法将信息从 app.js 传输到 pokemonDetail.js 文件。我该怎么做?感谢您的时间。
另外,我英语不好,所以这是我的项目。 https://github.com/yasoyase/PokemonExercise
这是我的 App.js
const [pokemons, setPokemons] = useState([]);
const getPokemonRequest = async () => {
const url = `https://pokeapi.co/api/v2/pokemon?offset=5&limit=5`;
const response = await fetch(url);
const fivePokemons = await response.json();
fivePokemons.results.forEach( async (pokemon) => {
const response = await fetch (pokemon.url);
const pokemonSpecs = await response.json();
setPokemons(currentPokemons => [...currentPokemons, pokemonSpecs])
})
};
useEffect(() => {
getPokemonRequest();
}, []);
return (
<div className="main-bg">
<div className='container'>
<div className='row'>
<PokemonList
pokemons={pokemons}
handleFavouritesClick={addFavouritePokemon}
favouriteComponent={AddFavourites}
/>
<Route path="/pokemon/:id" component={PokemonDetail} />
</div>
</div>
</div>
</div>
);
};
这是我的 Pokemonlist.js。我从那里获取了名称和 ID 到 App.js。
const PokemonList = (props) => {
const FavouriteComponent = props.favouriteComponent;
return (
<>
{props.pokemons.map((pokemon, index) => (
<div className="col-md-3 col-sm-6 my-5">
<StyledLink to={`pokemon/${pokemon.id}`}>
<Card>
<div className="card-outer">
<h5 className="card-header">{pokemon.id}</h5>
<h5 className="card">{pokemon.name}</h5>
</div>
</Card>
</StyledLink>
</div>
))}
</>
);
};
export default PokemonList;
如您所见,当我单击 pokemon 时,url 如下所示:例如 localhost/pokemon/5。但是,它没有显示有关该 ID 的更多信息。这是我的 PokemonDetail.js 文件。
function PokemonDetail(props) {
const FavouriteComponent = props.favouriteComponent;
const pokemons = props.pokemons;
return (
<div className="col-md-3 my-5">
{props.pokemons.map((pokemon, index) => (
<div className="card-outer w-100 p-2 rounded text-center">
<h5 className="card-header">{pokemon.abilities}</h5>
<img src={pokemon.sprites.other.dream_world.front_default} alt="pokemon-img"/>
</div>
))}
</div>
);
};
1个回答
.forEach 不支持异步函数 :)
请尝试使用 for await of
majkelS
2021-10-13