使用useState传递坐标时Google Maps JavaScript API告警问题
解决GoogleMapReact使用useState管理坐标时的"center or defaultcenter must be defined"警告
问题原因
你初始化useState时传入了空对象{},组件首次渲染时coordinates没有lat和lng属性,而GoogleMapReact要求center或defaultCenter必须是包含有效经纬度的对象,因此触发警告。
解决方案
方案1:初始化时设置默认有效坐标
将useState的初始值改为包含lat和lng的有效坐标对象,和你静态定义的格式一致:
const [coordinates, setCoordinates] = useState({ lat: 0, lng: 0 });
方案2:添加渲染条件判断
在渲染GoogleMapReact组件前,先判断coordinates是否包含有效经纬度,避免空对象传入组件:
{coordinates.lat !== undefined && coordinates.lng !== undefined && ( <GoogleMapReact bootstrapURLKeys={{ key: 'xxx' }} center={coordinates} defaultZoom={14} margin={[50, 50, 50, 50]} onChange={(e) => { setCoordinates({ lat: e.center.lat, lng: e.center.lng }); }} > {/* 子组件内容 */} </GoogleMapReact> )}
额外提示
无需同时设置center和defaultCenter——center是受控属性,会覆盖defaultCenter的初始值作用。如果用useState管理坐标,只保留center属性即可。
修改后的GoogleMapReact组件代码示例:
<GoogleMapReact bootstrapURLKeys={{ key: 'xxx' }} center={coordinates} defaultZoom={14} margin={[50, 50, 50, 50]} onChange={(e) => { setCoordinates({ lat: e.center.lat, lng: e.center.lng }); }} > {/* 子组件内容 */} </GoogleMapReact>
内容的提问来源于stack exchange,提问作者Immortal Phoenix
相关产品推荐
相关产品推荐

