簡體   English   中英

Google-maps-react:父組件傳遞的道具的價值

[英]Google-maps-react: Value of props passed by parent component

我正在使用與Google Map的React進行一個小項目,並且使用google-maps-react庫

每當我從服務器獲取數據並提取緯度和經度信息並將其傳遞給子元素(即HandleGoogleMap作為props並將其設置為initialCenter ,就會發生問題,該地圖將呈現一個latitude:0longitude:0

但是,當我將initialCenter值更改為僅數字時,它將正確呈現位置。 但是,我還記錄了緯度和經度道具,以確保它們不是數字。 這是代碼:

const HandleGoogleMap = props => {
  const { lat, lng } = props;

  // lat contains information of latitude
  // lng contains infromation of longitude

  console.log(lat);
  console.log(lng);

  return (
    <Map
      google={props.google}
      // when I change the value of lat and lng properties as numbers, it renders correctly 
      //but when I set values as props that the component passed by parent component, 
      //map renders lat: 0, lng:0 location
      initialCenter={{ lat: lat, lng: lng }}
      zoom={12}
    />
  );
};

export default GoogleApiWrapper({
  apiKey: "141423124123123123"
})(HandleGoogleMap);

我認為問題在於從api提取經緯度的異步特性。 您正在將InitialCenter與這些值一起使用,這可能是問題所在。

initalCenter:獲取包含緯度和經度坐標的對象。 加載時設置地圖中心。

中心:獲取包含緯度和經度坐標的對象。 如果要在初始渲染后重新渲染地圖,請使用此選項。

使用“ center”屬性代替來自api的數據,因為操作是異步的,一旦接收到數據,您將需要重新渲染地圖

<Map
  google={props.google}
  center={{ lat: lat, lng: lng }}
  zoom={12}
/>

問題在於道具沒有加載,這就是它的工作方式。 先使用props.loaded ,然后使用google={props.google} ,方法如下:

const HandleGoogleMap = props => {
  if (!props.loaded) return <div>Loading...</div>;


  return (
    <Map
      google={props.google}
      // when I change the value of lat and lng properties as numbers, it renders correctly 
      //but when I set values as props that the component passed by parent component, 
      google={props.google}
      zoom={12}
    />
  );
};

export default GoogleApiWrapper({
  apiKey: "141423124123123123"
})(HandleGoogleMap);

暫無
暫無

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

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