首页 > 解决方案 > 在循环中反应谷歌地图唯一键错误

问题描述

我得到了这个正在工作的 react-google-maps 组件,并且我从不同的位置接收了所有数据,但是控制台给了我这个错误消息:

Warning: Each child in a list should have a unique "key" prop.

在我的组件中,我添加了一个唯一的键 tho.. 有什么问题?

我就这样在页面上导入地图组件<Map />


import React from 'react'
import { GoogleMap, Marker, withGoogleMap, withScriptjs, InfoWindow } from "react-google-maps"
import { useStaticQuery, graphql } from "gatsby"

const Map = () => {

    const data = useStaticQuery(graphql`
{
    allContentfulHotels {
      nodes {
        id
        title
        location {
          lat
          lon
        }
      }
    }
  }
`)

    const {
        allContentfulHotels: { nodes: locations },
    } = data

    return (
        <>
            {locations.map(({ location }) => {
                console.log(location);
                return (
                    <GoogleMap
                        key={location.id}
                        defaultZoom={15}
                        defaultCenter={{
                            lat: location.lat,
                            lng: location.lon,
                        }}
                    >

                        <Marker
                            key={location.id}
                            position={{
                                lat: location.lat,
                                lng: location.lon,
                            }}
                        >
                        </Marker>

                    </GoogleMap>
                )
            })}
        </>
    )
}

const MapComponent = withScriptjs(withGoogleMap(Map));

const MyMap = () => (
    <div>
        <div
            style={{ width: '100%' }}
        >
            <MapComponent
                isMarkerShown
                loadingElement={<div style={{ height: `100%` }} />}
                containerElement={<div style={{ height: `500px` }} />}
                mapElement={<div style={{ height: `100%` }} />}
            />
        </div>
    </div>
)



export default MyMap


希望有人知道问题是什么。

标签: javascriptreactjs

解决方案


看起来您正在为<GoogleMap /><Marker />组件指定相同的键,请尝试为组件设置不同的键:

<GoogleMap
  key={`map-${location.id}`}
  defaultZoom={15}
  defaultCenter={{
    lat: location.lat,
    lng: location.lon,
  }}
>
  <Marker
     key={`marker-${location.id}`}
     position={{
       lat: location.lat,
       lng: location.lon,
     }}
  >
  </Marker>
</GoogleMap>

推荐阅读