[英]Google-maps-react: Value of props passed by parent component
我正在使用与Google Map的React进行一个小项目,并且使用google-maps-react库 。
每当我从服务器获取数据并提取纬度和经度信息并将其传递给子元素(即HandleGoogleMap
作为props
并将其设置为initialCenter
,就会发生问题,该地图将呈现一个latitude:0
和longitude: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.