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

InfoWindow is showing two infowindows using react-google-maps

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

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

这是我的代码:

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))

这也是我的噩梦:

这是我的 React 开发工具显示的内容,它只是主要的 InfoWindow

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

StrictMode is a tool that helps highlight potential problems in application. Like Fragment, StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.

StrictMode currently helps with:

  • Identifying components with unsafe lifecycles
  • Warning about legacy string ref API usage
  • Warning about deprecated findDOMNode usage
  • Detecting unexpected side effects
  • Detecting legacy context API

所以在我的例子中,问题是 StrictMode 正在检测我的地图组件上的意外副作用,这是故意 double-invoking 我的 useState 函数,使两个 InfoWindows 出现,而​​不是一个。

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

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