InfoWindow正在使用react-google-maps

问题描述

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

当挂钩状态更改时,InfoWindow会触发并显示自身,这很好。问题是InfoWindow有点小,没有任何信息会同时触发其他信息,我已经尝试了几个小时的错误查找,但找不到了,检查了代码,从浏览器中检查组件,但React开发人员工具无法识别出很少的InfoWindow。

这是我的代码

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

这也是我的噩梦:

enter image description here

这是我的react开发工具所显示的,这只是主要的InfoWindow

enter image description here

解决方法

让我头疼的是index.js上的React Strict Mode包装器,它使我的组件呈现了两次。根据React文档,

StrictMode是一个工具,可帮助突出显示应用程序中的潜在问题。 与Fragment一样,StrictMode不会呈现任何可见的UI。它会为其后代激活其他检查和警告。

StrictMode当前可帮助:

  • 识别具有不安全生命周期的组件
  • 有关旧式字符串引用API使用情况的警告
  • 有关过时的findDOMNode使用的警告
  • 检测出意外的副作用
  • 检测遗留上下文API

因此,在我的情况下,问题在于StrictMode正在检测我的地图组件上的意外副作用,这是有意两次调用了useState函数,使两个InfoWindows出现了,而不是一个。

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

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