我有一个地图组件,我需要在其中传递来自自定义 useSwr 挂钩的默认坐标。获取数据后,我将它们传递给状态并在值或未定义时呈现它。显然我做错了什么并且它无法正常工作,因为即使值未定义也会调用 Map 组件,这导致我收到此错误:
Failed prop type: Invalid prop `center` supplied to `o`.
这就是我处理状态的方式:
const {
locationDetails,
locationSessions,
isLoading,
isError,
} = useLocations();
const [mapCenter, setMapCenter] = useState({ lat: null, lng: null });
useEffect(() => {
setMapCenter({
lat: locationDetails?.location_lat,
lng: locationDetails?.location_lon,
});
}, [locationDetails]);
渲染时:
{mapCenter?.lat !== undefined &&
mapCenter?.lng !== undefined ? (
<GoogleMapReact
bootstrapURLKeys={{
key: "My api key",
}}
center={mapCenter}
zoom={14}
>
<IconMaps
name="PinDefault"
width="21px"
height="31px"
lat={parseFloat(location_lat)}
lng={parseFloat(location_lon)}
/>
</GoogleMapReact>
) : null}