如何在Typescript+React中通过索引获取元素?我一直收到错误:元素隐式具有“any”类型,因为类型“0”的表达式不能用于索引类型“{ code:字符串;名称:字符串;日期时间:string;}“。可能是个愚蠢的问题,但是我对Typescript没有太多的经验,我希望页面上分开显示[0]和[1]
const [result, setResult] = useState<ConversionData[]>([]);
type ConversionData = {
uuid: string;
airlineCode: string;
price: {
amount: number;
currency: string;
};
bounds: Array<{
departure: {
code: string;
name: string;
dateTime: string;
};
destination: {
code: string;
name: string;
dateTime: string;
};
duration: string;
}>;
};
useEffect(() => {
const api = async () => {
const data = await fetch("http://localhost:3001/flights").then((res) =>
res.json()
);
setResult(data);
};
api();
}, []);
return (
<div className="App">
{result.map((value) => {
return (
<>
{" "}
<div className="container">
{value?.bounds.map((newvalue) => {
const departure = newvalue.departure;
const destination = newvalue.destination;
const dates = new Date(departure.dateTime);
const dates2 = new Date(destination.dateTime);
return (
<>
<div>
<img
src={
"https://d1ufw0nild2mi8.cloudfront.net/images/airlines/V2/srp/result_desktop/" +
value.airlineCode +
".png"
}
/>
{departure.code}
<br />
do {destination.code}
<br />
Xxx:
{dates.getUTCHours()}
Xxx:
{dates2.getUTCHours()}
<br />
{dates.getUTCDate()}-
{dates.toLocaleString("en-US", { month: "short" })}-
{dates.getUTCFullYear()}
Xxx
{dates2.getUTCDate()}-
{dates2.toLocaleString("en-US", { month: "short" })}-
{dates2.getUTCFullYear()}
<div className="line" />
</div>
</>
);
})}
我在互联网上搜索并找到了解决方案与keyof,但它不工作
2条答案
按热度按时间gblwokeq1#
听起来
data
对象需要被转换为ConversionData
类型,当fetch
返回数据时,它不知道它是什么类型。setResult(data as ConversionData[]);
您可能首先需要将其强制转换为
unknown
:setResult(data as unknown as ConversionData[]);
hkmswyz62#
我做了一个不必要的双重Map。我需要bounds[0]。