簡體   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