[英]Calling function in child passed from parent in useEffect() hook, React
[英]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);
};
在上面的代码片段中,我试图调整 map 的大小以适合 window ,其中可以看到所有标记。 我希望每次添加新标记时都会发生这种情况,所以我认为将它放在 useEffect() function 中的好地方。 但是我不断收到错误:TypeError:无法读取未定义的属性“fitBounds”。 我很新的反应所以如果有人可以向我解释我如何实现这个功能我真的很感激。
我认为错误来自fitBounds()
function 中的这一行:
mapRef.current.fitBounds(bounds);
它可能会在 ref 完成设置之前尝试调用它。
如果 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.