【问题标题】:InfoWindow is showing two infowindows using react-google-mapsInfoWindow 正在使用 react-google-maps 显示两个信息窗口
【发布时间】:2021-02-19 16:46:06
【问题描述】:

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

当我的钩子状态发生变化时,我的 InfoWindow 会触发并显示自己,这很好。问题是一个小的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))

这也是我噩梦的图像:

这是我的 react 开发工具显示的,它只是主要的信息窗口

【问题讨论】:

    标签: reactjs google-maps react-hooks infowindow react-google-maps


    【解决方案1】:

    所以让我头疼的是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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-22
      • 2018-04-02
      • 2018-12-17
      • 2012-06-06
      • 2018-10-28
      • 2020-02-17
      • 2017-08-10
      • 1970-01-01
      相关资源
      最近更新 更多