InfoWindow 使用react-google-maps 显示两个信息窗口

Man*_*rte 11 google-maps infowindow reactjs react-google-maps react-hooks

我正在使用react-google-maps库,到目前为止我一直做得很好。我的应用程序从我的后端接收带有位置的 json,我正在映射它们以在地图上添加标记,它们显示得很好。这些标记有一个 OnClick 函数,用于设置 ReactHook 上的信息。

当我的钩子状态发生变化时,我的信息窗口会触发并自动显示,这很好。问题是一个小信息窗口没有与另一个同时触发的信息,我已经尝试找到错误几个小时了,但找不到它,我已经检查了代码,而且我是从浏览器检查组件,但反应开发人员工具无法识别那个小信息窗口。

这是我的代码:

function Map(props){
    const [selectedTienda, setSelectedTienda] = useState(null)
    const options ={
        styles: MapStyles,
        disableDefaultUI: true,
  
    }
    return(
        <GoogleMap
        defaultZoom={17} 
        defaultCenter={{lat: 29.0824139, lng: -110.966389}}
        options={options}

        >
            {props.items.map(tienda =>(
        <Marker
        key={tienda['tienda.id']}
        position={{
            lat: parseFloat(tienda['tienda.ubicacion.lat']),
            lng: parseFloat(tienda['tienda.ubicacion.lng'])
        }}
        onClick={()=>{
            setSelectedTienda(tienda);
        }}
        />
        ))}
         {selectedTienda ? (
            <InfoWindow position={{
                lat: parseFloat(selectedTienda['tienda.ubicacion.lat']),
                lng: parseFloat(selectedTienda['tienda.ubicacion.lng'])
            }}
            onCloseClick={()=>{setSelectedTienda(null)}}
            >
            <div><h4>This is the <br/>INFOWINDOW I WANT</h4></div>
            </InfoWindow>
        ): null}
               
               
        </GoogleMap>
    )
}
const MyMapComponent = withScriptjs(withGoogleMap(Map))
Run Code Online (Sandbox Code Playgroud)

这也是我的噩梦的图像:

在此输入图像描述

这是我的反应开发工具所显示的内容,这只是主信息窗口

在此输入图像描述

Air*_*cer 15

我找到了一个无需删除 React.StricMode 包装器即可工作的解决方案:

只需使用InfoWindowF代替InfoWindow(这也适用于 html 标签)。


Man*_*rte 8

所以让我头疼的是 React Strict Mode 包装器index.js,它渲染我的组件两次。根据 React 文档,

StrictMode 是一个有助于突出应用程序中潜在问题的工具。与 Fragment 一样,StrictMode 不会渲染任何可见的 UI。它为其后代激活额外的检查和警告。

StrictMode 目前可帮助:

  • 识别生命周期不安全的组件
  • 关于遗留字符串引用 API 使用的警告
  • 关于已弃用的 findDOMNode 用法的警告
  • 检测意外的副作用
  • 检测旧版上下文 API

因此,就我而言,问题在于 StrictMode 正在检测我的地图组件上的意外副作用,该组件故意双重调用我的 useState 函数,从而出现两个 InfoWindows,而不是仅一个。

我的解决方案是从我的文件中删除 React.StrictMode 包装器index.js,仅此而已,但我认为可能还有另一种解决方案来避免这些意外的副作用。

有关 StrictMode 及其工作原理的更多信息: https ://reactjs.org/docs/strict-mode.html