[英]React typescript how use types useState and render list in tsx
How can I set type to useState
and render list with map in React TypeScript?如何在 React TypeScript 中将类型设置为
useState
并使用 map 渲染列表?
I have a component:我有一个组件:
export type Item = {
name: string;
title: string;
};
export type ItemTypes = {
item: Item[];
};
export const ItemList: FC = () => {
const [items, setItems] = useState<ItemsTypes | []>([])
useEffect(() => {
let items = [
{
name: "A",
title: "B",
},
{
name: "C",
title: "D",
}
]
setItems()
}, [);
return (
<div>
{items?.map((item) => (
<>{item.name}</>
))}
</div>
)
}
And under .map line red stroke and saying:并在.map线红色笔划下并说:
any
Property 'map' does not exist on type 'ItemTypes | []'.
Where is my mistake?我的错误在哪里?
As defined ItemTypes
is not an array but instead an object having property item, hence the error.正如定义的
ItemTypes
不是一个数组,而是一个具有属性 item 的 object,因此出现错误。 Use Item[]
instead.请改用
Item[]
。
const [items, setItems] = useState<Item[]>([])
There are a couple of things wrong with the your implementation.您的实施存在一些问题。
First if you want to export
the type alias ItemTypes
you can set the type alias for ItemTypes
like this export type ItemTypes = Item[]
.首先,如果要
export
类型别名ItemTypes
,可以为ItemTypes
设置类型别名,例如export type ItemTypes = Item[]
。
Second, you are never calling setItems
with the items
you have created in useEffect
.其次,您永远不会使用您在
useEffect
中创建的items
调用setItems
。
Lastly, because you are trying to access the name
property on each item you should be checking item.length
in a conditional otherwise it will throw an error cannot access property name of undefined
if you do try to load the items asynchronously.最后,因为您尝试访问每个项目的
name
属性,所以您应该在条件中检查item.length
,否则如果您尝试异步加载项目,它将抛出错误cannot access property name of undefined
。
Solution解决方案
export type Item = {
name: string;
title: string;
};
export type ItemTypes = Item[];
export const ItemList: FC = () => {
const [items, setItems] = useState<ItemsTypes | []>([])
useEffect(() => {
let items = [
{
name: "A",
title: "B",
},
{
name: "C",
title: "D",
}
]
setItems(items)
}, []);
return (
<div>
{
items.length && items.map((item) => (<p>{item.name}</p>) )
}
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.