来自 useState 的值始终是地图事件回调中的初始值

Value from useState is always initial value in map event callback

我正在使用 @esri/react-arcgis 来显示基本地图。目标是在点击时发送请求以查找点击区域的一些数据。

这是我的地图:

<Map
    onLoad={handleMapLoad}
    onFail={handleMapLoadFail}
    onClick={handleMapClick}
    ... // bunch of other properties (basemap, styles etc)
></Map>

我的问题是,当 onClick 触发(并且 handleMapClick 被调用)时,组件 useState 的值始终是初始值。 它是这样定义的:const [mapViewReference, setMapViewReference] = useState(null);.

它不应该总是空的,因为:

  1. handleMapLoad 在开始时被调用。它设置以下状态:setMapViewReference(view);view 是 属性 我直接从 esri 库中获取。
  2. 之后,我点击地图,执行回调
  3. 如果我从虚拟按钮调用 handleMapClick,state/value 将是正确的。

这是否可以由 useCallback 或其他挂钩处理?我不确定这是否是 esri 库的问题...

这就在我的return(功能组件)之前:

const handleMapClick = async event => {
    console.log(mapViewReference); // This is always null, unless I call the function manually from a dummy button
    const point = mapViewReference.toMap(event);
    const response = await featureLayerReference.queryFeatures({...});
};

是的,我曾经遇到过与 react-map-gl 相同的问题。我认为它是组件安装时的 onClick 函数的备忘录,并且当地图呈现任何状态更改时不会更新它。我所做的是在地图单击事件触发时触发 setState,并在事件状态更改时在 useEffect 中执行所有操作:

const [event,setEvent]= useState()

useEffect(()=>{
if(event){
   console.log(mapViewReference); // This is always null, unless I call the function 
     manually from a dummy button
    const point = mapViewReference.toMap(event);
    const response = await featureLayerReference.queryFeatures({...});
}
},[event])

对于地图组件:

<Map
    onLoad={handleMapLoad}
    onFail={handleMapLoadFail}
    onClick={setEvent}
    ... // bunch of other properties (basemap, styles etc)
></Map>