我嘗試了不同的方法來解決這個問題,但無法成功。
我有以下 Reactjs 組件:
import EventItem from "../EventItem";
type Props = {
events: [id: number, attributes: { slug: string; name: string; }];
};
const EventList = ({ events }: Props) => {
return (
<section>
<div className="max-w-7xl mx-auto px-4 mb-5">
<div className="max-w-sm mx-auto md:max-w-none bg-events-list p-4" data-aos="fade-up">
<div className="grid gap-12 md:grid-cols-4 md:gap-x-4 md:gap-y-8 items-start">
{events?.map((eventMap, index) => (
<EventItem
key={index}
url={`/e/${eventMap.attributes.slug}`}
name={eventMap.attributes.name}
/>
))}
</div>
</div>
</div>
</section>
);
};
export default EventList;
打字稿警告說
Property 'attributes' does not exist on type 'number | { slug: string; name: string; }'.
Property 'attributes' does not exist on type 'number'.
我的資料結構是:
{
"id": 2,
"attributes": {
"name": "Event Name",
"slug": "event-name",
}
}
我該如何解決?我的型別道具有什么問題?謝謝!
uj5u.com熱心網友回復:
type Props = {
events: [id: number, attributes: { slug: string; name: string; }];
};
你的打字說,事件等于一個帶有 id 的陣列,以及一個包含{ slug: string; name: string; }
但是要實作你想要的,你必須像這樣輸入
type Props = {
events: Array<{id: number, attributes: { slug: string; name: string; }}>;
};
現在,events是具有您的結構的物件陣列:)
uj5u.com熱心網友回復:
嘗試以下操作:
type Props = {
events: { id: number, attributes: { slug: string; name: string; } } [];
};
uj5u.com熱心網友回復:
type Props = {
events: [id: number, attributes: { slug: string; name: string; }];
};
似乎事件型別應該是物件而不是陣列。你能試試這個嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/455414.html
標籤:javascript 反应 打字稿
下一篇:有條件的背景圖片
