我正在尝试从API获取数据,并在React with typescript中将数据显示到卡片列表中。由于我是React in Typescript的新手,不确定如何解决此错误,或者我错过了什么。
这是我得到的错误:键入"{子项:字符串[];密钥:number ;}"不能赋给类型" IntrinsicAttributes & Props "。类型" IntrinsicAttributes & Props "上不存在属性" children "。
这是密码:
interface Props {
pokemonItem: PokemonItem;
}
export const PokemonCardList = (props: Props) => {
const { pokemonItem } = props;
const {
id = '',
name = '',
weight = '',
height = '',
abilities = '',
} = pokemonItem;
const [pokemon, setPokemon] = React.useState<PokemonItem[]>([]);
const [loadItems, setLoadItems] = React.useState(API_URL);
const getPokemons = async () => {
setLoading(true);
const response: any = await fetch(loadItems);
const data = await response.json();
setLoadItems(data.next);
setPokemon(data.results[0].name);
setLoading(false);
const getEachPokemon = (result: any) => {
result.forEach(async (element: any) => {
const response = await fetch(
`https:pokeapi.co/api/v2/pokemon/${element.id}`
);
const data = await response.json();
// // setPokemon((currentArrayList) => [...currentArrayList, data]);
pokemon.push(data);
});
};
getEachPokemon(data.results);
await console.log(pokemon);
};
React.useEffect(() => {
return getPokemons();
}, []);
return (
<div>
{pokemon &&
pokemon.map((item, index) => (
<PokemonCard key={index}>
{item.name} {item.height} {item.weight} {item.abilities}
</PokemonCard>
))}
</div>
);
};
PokemonCard组件:
interface Props {
pokemonItem: PokemonItem;
}
const PokemonCard = (props: Props) => {
const { pokemonItem } = props;
const {
id = '',
name = '',
weight = '',
height = '',
abilities = '',
} = pokemonItem;
const [imageLoaded, setImageLoaded] = React.useState(false);
const urlImage = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png?raw=true`;
return (
<div imageLoaded={imageLoaded}>
<div
src={urlImage}
onLoad={() => setImageLoaded(true)}
/>
<div>
Name: {name}
Height: {height}
Weight: {weight}
Abilities: {abilities}
</div>
</div>
);
};
4条答案
按热度按时间70gysomp1#
使用
react
中的PropsWithChildren
:q8l4jmvw2#
根据您对
PokemonCard
组件的定义,应该按如下方式传递pokemonItem
:我已经替换了
key
prop,因为不推荐使用索引作为键(参见文档),您可以使用项的id来代替,并且您需要更新PokemonCard
组件的prop接口,以便额外的key
prop不会破坏验证:vddsk6oq3#
尝试以下操作(为组件添加类型):
第一个月
qv7cva1a4#