簡體   English   中英

使用 Map 函數編寫 React 組件時,對象不能作為 React Child 有效

[英]Objects are Not Valid as React Child when using Map Function to write React Components

我正在構建一個 react native 應用程序,它具有地圖功能,可以在地圖上為不同地方的數組創建標記。 為此,我使用 API 來獲取坐標,因此需要使用異步函數,如下所示:

<MapView style={styles.mapStyle}>
  {this.state.isLoading ? null : 
    this.state.places.map(async (place) => {
      const coords = await fetchCoords(place)

      return (
        <MapView.Marker
          coordinate = {coords}
        />
      )
    })
  }
</MapView>

但是這段代碼給出了錯誤: Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}) 我猜這個錯誤是因為我錯誤地實現了異步映射函數。 應該是什么?

傳遞給 Market 組件的坐標道具需要是一個對象或數組(表示緯度/經度、x/y 等),但是傳遞的內容是一個承諾。

“const coords = await fetchCoords(place)”部分不應該直接在你的渲染方法中發生,而是在其他地方,比如 componentDidMount 然后保存到狀態,或者在更高階的組件中進行異步調用並將結果作為道具傳遞. 這將確保 fetchCoords 函數不會在每次重新渲染時被不必要地調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM