reactjs - React:如何解决:“IntrinsicAttributes & Props”类型上不存在属性“children”
问题描述
我正在尝试从 API 获取数据并将数据显示到 React with typeScript 中的卡片列表中。由于我是 Typescript 中的 React 新手,不知道如何解决这个错误或者我错过了什么。
这是我得到的错误: Type '{ children: string[]; 键:数字;}' 不可分配给类型 '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>
);
};
小精灵卡组件:
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>
);
};
解决方案
根据您对PokemonCard
组件的定义,您应该传递pokemonItem
如下内容:
<PokemonCard pokemonItem={item} key={item.id} />
我已经替换了key
道具,因为不建议将索引用作键(请参阅文档),您可以使用项目的 id 代替。并且您需要更新PokemonCard
组件的 prop 接口,以便额外的key
prop 不会破坏验证:
interface Props {
pokemonItem: PokemonItem;
key: string;
}
推荐阅读
- node.js - Node.js 中的 Python `getattr` 等价物是什么?
- azure - Azure Kubernetes 上的自定义域和大使 API 网关
- android - 为什么永远不会调用 onLocationchanged
- css - 如何在 scss 中获取当前视口大小?
- c++ - Flex C++ - 弹性块内的#ifdef
- ruby-on-rails - 将 json 传递给控制器时,rails 上的 ActionController::UnknownFormat 测试
- hbase - hbase的region太多有什么影响?
- architecture - 在发布-订阅消息系统中同步新的/取消同步的微服务
- alloy - 程序、数据和结果之间的三元关系的有意义的字段名称?
- mongodb - 尝试使用 mongoose 连接到 MongoDB 集群时,“MongoError:ismaster 中的 setName 与提供的连接 setName 不匹配”