Graphql 响应错误。字符串不能表示 JSON 的值

Graphql response error. String cannot represent value of JSON

我在 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

出问题了

这里有多个错误

好吧,你使用的是 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 之类的东西。通过阅读函数,它非常清楚它在做什么。