繁体   English   中英

React.js - 未捕获的类型错误:无法读取未定义的属性(硬编码数据时不会发生)

[英]React.js - Uncaught TypeError: Cannot read properties of undefined (does not happen when data is hardcoded)

我当前的代码发出 GET 请求来获取数据,然后将数据显示为 Google 地图上的标记。 我已经省略了以下代码片段中的一些代码以使其更易于阅读,但我可以向您保证,我删除的代码不是原因。

如果我 map offline ,则位置的标记完美地显示在 map 上。 如果我改为将其更改为points ,我在路由调用中设置,那么我将收到错误App.js:66 Uncaught TypeError: Cannot read properties of undefined (reading 'cameras')

我该如何解决?

function App() {
  const [points, setPoints] = useState([]);

  useEffect(() => {
    fetch('/cameras-by-date').then(res => res.json()).then(data => {
      setPoints(data);
    });
  }, []);

  const offline = [
    {
      "cameras": [
        {
          "location": "ANZAC HWY, ASHFORD",
          "position": {
            "lat": -34.9502955,
            "lng": 138.575806
          }
        }
      ],
      "date": "03/09/2022"
    }
  ]

  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: MAPS_API_KEY
  })

  const [map, setMap] = React.useState(null)

  const onLoad = React.useCallback(function callback(map) {
    const bounds = new window.google.maps.LatLngBounds(center);
    map.fitBounds(bounds);
    setMap(map)
  }, [])

  if (!isLoaded) {
    return
  }

  return (
    <div className="App">
      <header className="App-header">
        <GoogleMap
          mapContainerStyle={containerStyle}
          center={center}
          zoom={10}
          options={options}
          onLoad={map => setMap(map)}
        >
          {offline[0].cameras.map(({ position }) => (
            <Marker
              position={position}
            >
            </Marker>
          ))}
        </GoogleMap>

      </header>
    </div >
  );
}

export default App;

{points[0]?.cameras.map(({ position }) => (为我工作。

经过一番搜索,在这个线程中找到了它: React JS fetching data (error: Cannot read properties of undefined)

请尝试这样

offline[0] && offline[0].cameras && offline[0].cameras.map(({ position }) => ( ...

您可能会尝试使用可选链接,因为当从服务器/数据库接收数据时,一开始它是未定义的。 所以也许你可以用你的 map function 做类似的事情:

{points?.[0]?.cameras?.map((point, index) => (
    <Marker
     key={index}
     position={position}
     >
     ....
     </Marker>
))}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM