我要做的是映射一個陣列,其中包含具有屬性的物件和其他嵌套物件,以回傳我之前匯入的 React 組件。
我從 TypeScript 得到這個
“從不”型別上不存在屬性“max_temp”。
“從不”型別上不存在屬性“min_temp”。
我的猜測是 TypeScript 會抱怨,因為它不知道我的陣列里面包含嵌套的物件,所以它說我永遠不會得到任何呼叫它的東西。這是我的代碼(下面我將發布截圖)
import React from "react";
import Card from "./Card";
type Props = {
cities: [];
};
const Cards: React.FC<Props> = ({ cities }) => {
return (
<div>
{cities.map(({ name, main, weather }) => {
return (
<Card
name={name}
max={main.max_temp}
min={main.min_temp}
img={weather[0].icon}
onClose={() => alert({ name })}
/>
);
})}
</div>
);
};
export default Cards;

uj5u.com熱心網友回復:
你必須輸入你的城市陣列,例如類似的東西(你的道具Card可能需要實際上不同的型別):
import React from "react";
import Card from "./Card";
type Props = {
cities: [
{ name: string,
main: {
max_temp: number,
min_temp: number
},
weather: Array<{icon: any}>
}];
};
const Cards: React.FC<Props> = ({ cities }) => {
return (
<div>
{cities.map(({ name, main, weather }) => {
return (
<Card
name={name}
max={main.max_temp}
min={main.min_temp}
img={weather[0].icon}
onClose={() => alert({ name })}
/>
);
})}
</div>
);
};
export default Cards;
uj5u.com熱心網友回復:
您尚未在 Props 中定義城市型別。
type Props = {
cities: []; <--- what is this array of?
};
例如:
type Props = {
cities: CityType[];
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/421506.html
標籤:
