Heim  >  Fragen und Antworten  >  Hauptteil

Einfache Möglichkeit, JSON-Daten mithilfe von React-Query und Axios in TypeScript-Objekte zu analysieren

Dies sind die JSON-Daten, die ich vom Server erhalte:

{"id" : 1, "text_data": "example data"}

Jetzt versuche ich, diese JSON-Daten in ein TS-Objekt zu analysieren:

export interface IncomingData {
  id: number;
  text_data: string;
}

function App() {

  // 它可以重写为 'await axios.get<IncomingData>('http://localhost:3000/api')' 并删除 useQuery 的 turbofish 语法。没有任何变化。
 
  let json_object = useQuery<IncomingData>("data_ex_key", async () => {
    try {
      const response = await axios.get('http://localhost:3000/api');
      return response.data;
    } catch (err) {
      throw err
    }
  });

  if (json_object.data !== undefined) {
    console.log(json_object.data.text_data);
  }
}

In der Konsole bekomme ich undefined的文本。问题是我已经使用了react-query调试器调试了这段代码,并显示json_object查询已成功获取数据。我可以访问这些数据,但无法访问其属性,如text_data.

P粉621033928P粉621033928249 Tage vor424

Antworte allen(1)Ich werde antworten

  • P粉310931198

    P粉3109311982024-01-17 00:36:18

    找到了一个解决方案。

    需要使用数组而不是单个对象。

    Antwort
    0
  • StornierenAntwort