从次要组件的api通过map返回信息错误(React Typescript)



我试图返回一个带有PokeApi信息的页面,但它只是返回一个没有信息的白屏。我通过API管理返回所有口袋妖怪,但我试图为每个口袋妖怪选择的信息创建一个页面。

PokemonPage文件夹

import * as C from './styles';
import { useEffect, useState } from 'react';
import { useApi } from '../../Hooks/useApi';
import { useParams } from 'react-router-dom';
import { SinglePokemonTS } from '../../types/SinglePokemon';
import SinglePokemon from '../../Components/SinglePokemon';
const PokemonPage = () => {
const api = useApi();
const { name } = useParams();
const [loading, setLoading] = useState(true);
const [pokemon, setPokemon] = useState<SinglePokemonTS[]>([]);
useEffect(() => {
if (name) {
getPokemon(name);
console.log(pokemon)
} 
}, [loading])
const getPokemon = async (param: string) => {
const pokemon = await api.getPokemon(param)
setPokemon(pokemon)
setLoading(false);
}

return (
<C.PokemonPage>
{loading &&
<div>Loading...</div>
}
{!loading &&
pokemon.map((item) => (
<SinglePokemon
sprites={item.sprites}
id={item.id}
name={item.name}
types={item.types} 
/>
))
}
</C.PokemonPage>
)
}
export default PokemonPage

SinglePokemon组件:

import * as C from './styles';
import { SinglePokemonTS } from '../../types/SinglePokemon'
const SinglePokemon = ({
id,
name, 
sprites,
types,
}: SinglePokemonTS) => {
return (
<C.PokemonData>
<img src={sprites.front_default} alt="" />
<h1>{name}</h1>
<p>id: {id}</p>
{types &&
<p>tipo: <span>{types.map(item => item.type.name)}</span></p>
}
</C.PokemonData>
)
}
export default SinglePokemon

SinglePokemon。ts型:

export interface SinglePokemonTS {
id: number;
name: string;
sprites: {
front_default: string;
};
types: {
type: {
name: string;
}
} []
}

控制台错误:

index.tsx:33 Uncaught TypeError: pokemon.map is not a function
at PokemonPage (index.tsx:33:1)
at renderWithHooks (react-dom.development.js:16305:1)
at updateFunctionComponent (react-dom.development.js:19588:1)
at beginWork (react-dom.development.js:21601:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
react-dom.development.js:18687 The above error occurred in the <PokemonPage> component:
at PokemonPage (http://localhost:3000/main.f4037b6ee75101fad614.hot-update.js:198:66)
at MainRoutes (http://localhost:3000/static/js/bundle.js:1377:69)
at App
at Router (http://localhost:3000/static/js/bundle.js:44818:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:43627:5)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

您正在将pokemon列表设置为您从API调用获得的响应。我看不到响应,但我猜有一些数据,你应该设置口袋妖怪数组…你可以把你从api得到的响应发给我,我会试着帮你解决这个问题

相关内容

最新更新