【问题标题】:Object is possibly null using "useEffect"使用“useEffect”对象可能为空
【发布时间】:2021-03-14 01:21:03
【问题描述】:

我正在尝试使用 GoogleMaps 设置边界,并且即使在进行错误检查时也收到“对象可能为空”错误。

背景是我试图在状态变化时将地图移动到我的标记并增加边界以显示所有标记。

其他相关文章(例如添加空检查)在修复此错误方面没有成效。

  const [map, setMap] = React.useState(null)
  const [loc, setLoc] = React.useState({lat: 0, lng: 0})
  const [stores, setStores] = React.useState([])


  const onLoad = React.useCallback(function callback(map) {
    navigator.geolocation.getCurrentPosition((position) => { 
      console.log("Got position", position.coords);
      setLoc({
        lat: position.coords.latitude,
        lng: position.coords.longitude
      });

    });
    setMap(map)
  }, [])

  useEffect(() => {
    if (stores && map !== null) {
      const bounds = new window.google.maps.LatLngBounds();
      stores.forEach(store => {
        const latlng = new google.maps.LatLng(
          //Get Lat
          //Get Lon
        );
        bounds.extend(latlng)
      });
      map.fitBounds(bounds);
    }
  }, []);
...
  return (
    <LoadScript
      googleMapsApiKey="AIzaSyDTd3ejyeGgdFBOZvaqwoa_7U2e2EJMc1w"
    >
      <Input/>
      <GoogleMap
        mapContainerStyle={containerStyle}
        center={loc}
        zoom={10}
        onLoad={onLoad}
        onUnmount={onUnmount}
      >
...

每当状态发生变化时,我是否正确使用“useEffect”来更新地图上的边界?每当“商店”变量发生变化时,我都想更新地图的边界

【问题讨论】:

  • 你可以使用optional chaining
  • 我会使用这样的可选链接吗:map?.fitBounds(bounds)
  • 如果我尝试使用可选链,我会得到“从不”类型上不存在属性“fitBounds”。 map?.fitBounds(bounds)

标签: reactjs typescript react-google-maps


【解决方案1】:

您没有使用正确的 useEffect 方式,useEffect 应该在第二个参数的依赖数组中包含所有变化的变量。 useCallback 也是如此,它都期望变量列表会发生变化,以了解何时必须再次调用内部函数。

您可以添加exhaustive-deps lint 规则以在开发模式下抛出警告。

const onLoad = React.useCallback(function callback(map) {
  navigator.geolocation.getCurrentPosition((position) => {
    console.log("Got position", position.coords);
    setLoc({
      lat: position.coords.latitude,
      lng: position.coords.longitude,
    });
  });
  setMap(map);
}, [map]);

useEffect(() => {
  if (stores && map !== null) {
    const bounds = new window.google.maps.LatLngBounds();
    stores.forEach((store) => {
      const latlng = new google.maps.LatLng();
      //Get Lat
      //Get Lon
      bounds.extend(latlng);
    });
    map.fitBounds(bounds);
  }
}, [map, stores]);

【讨论】:

  • 我尝试将依赖变量添加到参数数组中,但仍然出现错误
  • 对象可能为“空”。在“map.fitBounds(bounds)”行
  • bounds null?
  • Bounds 在 useEffect 函数的开头被初始化。即使我将它移到 if 语句之外,我仍然会收到错误
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 2021-08-27
  • 2021-03-09
  • 2019-11-10
  • 2021-08-08
相关资源
最近更新 更多