【发布时间】:2022-01-11 02:50:05
【问题描述】:
我用过以下
模板文件 -- 读取 json 文件,因为它是给定格式的
export type GList = {
hop_num: number,
hostname: string,
ip_address: string,
latitude: number,
longitude: number;
rtt: string;
};
export type IUList = {
hop_num: number,
hostname: string,
ip_address: string,
latitude: number,
longitude: number;
rtt: string;
};
export type iData = {
array_google : GList[];
array_iu : IUList[];
time : number;
};
export type ResponseData = {
ids: iData;
};
组件文件
import { ReactChild } from "react";
import { GList } from "../types";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
interface Props {
google_list:GList[];
}
const Map_test: React.FunctionComponent<Props> = ({
google_list
}) => {
return(
<div id="sample">
<MapContainer>
{google_list.map((trset) => (
<Marker
key={trset.hop_num}
position={[trset.latitude, trset.longitude]}
></Marker>
))}
</MapContainer>
</div>
);
};
export default Map_test;
App.tsx 文件
import { useEffect, useState } from "react";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import "./App.css";
import trdata from "./data/tracedata.json";
import { Line } from "react-chartjs-2";
import { Chart } from "chart.js";
import type { ResponseData, IUList, GList, iData } from "./types";
import Map_test from "./components/Map_test";
const App: React.FunctionComponent = () => {
const [data, setData] = useState<ResponseData | undefined>(undefined);
const fetchData = async () => {
const result = await fetch("http://18.223.114.82/pastfive");
const data :ResponseData = await result.json();
const id_num : number = 1;
setData(data);
console.log(data);
};
useEffect(() => {
fetchData();
}, []);
// console.log(trdata[1]['google.com']);
return (
<div id="sample">
<div id="heading">
<h1>TraceRoute Analysis</h1>
</div>
<div>
{data ? (
<>
<div>
{data ? (
<>
<Map_test
google_list={data.ids.array_google} \\ error at this line
/>
</>
) : (
"Loading..."
)}
</div>
</>
) : (
"Loading..."
)}
</div>
<div id="myData"></div>
<script></script>
</div>
);
};
export default App;
您好,我在网上搜索了多个资源,但我认为这是一个相当复杂的 JSON 文件,我正在尝试阅读。即使我描述了正确的数据类型,它也无法获取数据并抛出以下错误。
TypeError: Cannot read properties of undefined (reading 'array_google')
非常感谢您对此提供一点帮助。
【问题讨论】:
标签: javascript html jquery reactjs typescript