我在 graphql 有一個錯誤。我正在嘗試通過 JSON 資料獲取機場名稱。我需要一個專案(機場名稱),但我收到了一系列專案,其中包括城市、國家、地理位置等。這是我正在嘗試的代碼......
const getNameOfAirport = (name:any)=>{
return AIRPORTS.filter((i)=>{
if(i.iata_code === name){
return i.name.length;
}
})
}
當我運行 condole.log(getNameOfAirport("BLR")) 我收到
[
{
name: 'Bangalore',
city: 'Bangalore',
country: 'India',
iata_code: 'BLR',
_geoloc: { lat: 12.949986, lng: 77.668206 },
links_count: 195,
objectID: '3131'
}
]
我需要回應
Bangalore
任何答案都非常感謝。讓我知道我在哪里做錯了。
注意:我正在使用打字稿。正如我所料,它與 JSX 一起作業。TS出了問題
uj5u.com熱心網友回復:
這里有多個錯誤
好吧,您使用 Typescript,但any輸入您的型別。為什么你甚至首先使用打字稿?但這是另一個問題:
const getNameOfAirport = (name:any)=>{
return AIRPORTS.filter((i)=>{
if(i.iata_code === name){
return i.name.length;
}
})
}
我看到你使用AIRPORTS,它是一個陣列。但是你沒有將它傳遞給函式,所以陣列在函式之外。副作用很糟糕。你應該避免這種情況。
Array.filter()我猜是錯誤的方法。你應該試試.find()
您還應該創建一個介面。試試這個:
const getNameOfAirport = (
airports: Airport[],
name: string
): string | undefined => {
return airports.find((airport) => airport.iata_code === name)?.name;
};
interface Airport {
name: string;
city: string;
country: string;
iata_code: string;
_geoloc: {
lat: number;
lng: number;
};
links_count: number;
objectID: string;
}
然后你呼叫它:
getNameOfAirport(AIRPORTS, "BLR")
旁注:這個名字getNameOfAirport有點不好命名。我建議使用類似getAirportNameByIataCode. 通過閱讀該功能,它非常清楚它在做什么。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/468686.html
標籤:打字稿 图形 express-graphql
上一篇:從axios函式獲取回應
