简体   繁体   English

在反应中从 useEffect 中调用单独的 function

[英]Calling a seperate function from within useEffect in react

  const [markers, setMarkers] =  React.useState([]);

  const mapRef = React.useRef();

  React.useEffect( () => {
    fitBounds();
  }, [markers])

  const fitBounds = () => {
    const bounds = new window.google.maps.LatLngBounds();
    markers.map(place => {
      bounds.extend(place);
    });
    mapRef.current.fitBounds(bounds);
  };

In the above code snippet im trying to resize the map to the fit the window in which all markers can be seen.在上面的代码片段中,我试图调整 map 的大小以适合 window ,其中可以看到所有标记。 I want this to occur everytime a new marker is added so I though a good place to put it would be in the useEffect() function.我希望每次添加新标记时都会发生这种情况,所以我认为将它放在 useEffect() function 中的好地方。 However I keep getting the Error: TypeError: Cannot read property 'fitBounds' of undefined.但是我不断收到错误:TypeError:无法读取未定义的属性“fitBounds”。 Im fairly new to react so if someone could explain to me how I can achieve this functionality Id really appreciate it.我很新的反应所以如果有人可以向我解释我如何实现这个功能我真的很感激。

I think the error is coming from this line within your fitBounds() function:我认为错误来自fitBounds() function 中的这一行:

mapRef.current.fitBounds(bounds);

It's likely trying to call it before the ref has finished setting.它可能会在 ref 完成设置之前尝试调用它。

Try bailing out of the function early if it's not ready, eg:如果 function 尚未准备好,请尝试尽早退出,例如:

  const fitBounds = () => {
    if (!mapRef.current) return;

    const bounds = new window.google.maps.LatLngBounds();
    markers.map(place => {
      bounds.extend(place);
    });
    mapRef.current.fitBounds(bounds);
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM