英文:
Double map in React+Typescript
问题
下面是你要的代码部分的中文翻译:
也许我漏掉了什么,但在这种情况下,我应该如何正确地进行双重映射?因为我在第二个映射上遇到了错误:属性“map”在类型“{ departure: { code: string; name: string; dateTime: string; }; destination: { code: string; name: string; dateTime: string; }; duration: string; }”上不存在。
const [result, setResult] = useState<ConversionData[]>([]);
type ConversionData = {
uuid: string;
airlinesCode: string;
price: {
amount: number;
currency: string;
};
bounds: {
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);
console.log(result);
};
api();
}, []);
return (
<div className="App">
<h1>
{result?.map((value) => {
console.log(value)
return (
<div>
<div>{value.price.amount}</div>
{value.bounds.map((newvalue: any) => {
<div>{newvalue.departure.name}</div>
})}
</div>
);
})}
</h1>
</div>
);
需要映射的部分是在result
中的bounds
下的departure
属性中的name
。如果你需要获取这个属性,你可以在map
函数中使用value.bounds.departure.name
。
英文:
Maybe I'm missing something, but how should I properly double map in this case? Bcs I have error on secon map : Property 'map' does not exist on type '{ departure: { code: string; name: string; dateTime: string; }; destination: { code: string; name: string; dateTime: string; }; duration: string; }
const [result, setResult] = useState<ConversionData[]>([]);
type ConversionData = {
uuid: string;
airlinesCode: string;
price: {
amount: number;
currency: string;
};
bounds: {
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);
console.log(result);
};
api();
}, []);
return (
<div className="App">
<h1>
{result?.map((value) => {
console.log(value)
return (
<div>
<div>{value.price.amount}</div>
{value.bounds.map((newvalue:any)=>{
<div>{newvalue.departure.name}</div>
})}
</div>
);
})}
</h1>
</div>
);
I've searched the internet for something similar, but I've hit the starting point, and I need to get to bounds -> departure -> name
答案1
得分: 0
你的类型ConversionData中的边界是对象。但在你的数据截图中,边界应该是数组。
bounds: Array<{
departure: {
code: string;
name: string;
dateTime: string;
};
destination: {
code: string;
name: string;
dateTime: string;
};
duration: string;
};
}>;
英文:
Bounds in your type ConversionData is object. But at you data screenshot bounds should be array.
bounds: Array<{
departure: {
code: string;
name: string;
dateTime: string;
};
destination: {
code: string;
name: string;
dateTime: string;
};
duration: string;
};
}>;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论