React:如何解决源有1个元素,但目标只允许0?



我试图从API获取数据并显示它们,但是当我尝试对数据数组进行扩展运算符时,我得到了错误。有人能帮帮忙吗?

这是我得到的错误:

参数类型'(currentArrayList: []) =>[any]'不能赋值给'SetStateAction<[]>'类型的参数。类型"(currentArrayList:[]) =比;[any]'不能赋值给类型'(prevState: []) =>[]"。类型"[any]"不能赋值给类型"[]"。源有1个元素,但目标只允许0个元素。TS2345

这是代码:

const API_URL = 'https:pokeapi.co/api/v2/pokemon';
interface Props {
pokemonItem: PokemonItem[];
children: React.ReactNode | React.ReactNode[];
} 

export const PokemonContainer: React.FC = (props) => {
const [pokemon, setPokemon] = React.useState([]);
const [loadItems, setLoadItems] = React.useState(API_URL);
const getPokemons = async () => {
const response: any = await fetch(loadItems);
const data = await response.json();
setLoadItems(data.next);
setPokemon(response.data.results[0].name);
console.log(response.data.results);
const getEachPokemon = (result: any) => {
result.forEach(async (element: any) => {
const response = await fetch(
`https:pokeapi.co/api/v2/pokemon/${element.name}`
);
const data = await response.json();
setPokemon((currentArrayList) => [...currentArrayList, data]);
});
};
getEachPokemon(data.results);
await console.log(pokemon);
};
React.useEffect(() => {
getPokemons();
}, []);

:

export interface PokemonItem {
id: number;
name: string;
height: string;
weight: string;
abilities: string;
}

这是因为const [pokemon, setPokemon] = React.useState([]);没有键入。如果你给useState添加一个类型,它就不会抱怨了,例如:React.useState<any[]>([]).

然而,我建议不要使用任何类型,而是实际创建一个反映口袋妖怪外观的类型。我还建议不要在代码的其他地方使用任何类型,并尽可能多地使用类型:)

最新更新