0

我有一个地图组件,我需要在其中传递来自自定义 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}                     
                      
4

1 回答 1

1

所以你说如果你这样做

{mapCenter?.lat != undefined && // non-strict
                    mapCenter?.lng != undefined ? ( // non-strict
                      <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}                     
                      

它仍然返回地图?尝试返回除此之外的其他内容null(例如一段文本,仅用于测试目的),因为我觉得可能存在除三元以外的其他问题。

于 2021-01-14T12:32:55.760 回答