【发布时间】:2021-05-02 14:37:21
【问题描述】:
我正在使用 react 和 react-leaflet 制作地图。 React Leaflet 有一个名为 FeatureGroup 的类,我想在第一次渲染时使用 React 中的 useRef 钩子访问它,然后访问 useEffect 函数中的值。然而,在初始渲染时,ref 是未定义的(markerRef.current 返回 null)。只有在我对代码进行任何类型的更改后,保存并重新加载 React 应用程序才会获得值
你能告诉我我做错了什么以及如何使 markerRef.current 在初始渲染时不为空吗?
请在下面找到该组件的缩写代码:
import {useRef} from 'react';
import {FeatureGroup, //... } from 'react-leaflet';
const MapView = ({breweries}) => {
const markerGroupRef = useRef(null);
//...
useEffect(() => {
if(markerGroupRef.current) {
//here I want to access a method called getBounds() which is in the markerGroupRef.current object
//but markerGroupRef.current has null value and so it doesn't execute
//when making a save change and react app reloads it has the FeatureGroup class as value as expected
console.log(markerGroupRef.current)
}
}, [markerGroupRef])
//...
return (
<FeatureGroup ref={markerGroupRef}>
{breweries && breweries.map(brewery => <Brewery key={breweries.indexOf(brewery)} brewery={brewery}/>)}
{breweryStore && breweryStore.searchLocation && <LocationMarker markerPosition={{lat: breweryStore.searchLocation.lat, lng: breweryStore.searchLocation.lon}}/>}
</FeatureGroup>
);
}
【问题讨论】:
-
你如何尝试使用 markerGroupRef
-
如果你不传递初始值,它在第一次渲染时总是未定义
-
这是因为 ref 在渲染时间之后更新,因为 DOM 元素在渲染时间之前不存在。 stackoverflow.com/questions/22238320/…
-
@Mr.Robot 感谢您的链接。不过,我不确定如何将其解决方案转换为带有钩子的功能组件。我还更新了我的问题,向您展示我如何尝试在 useEffect 函数中访问它。
标签: reactjs react-leaflet