javascript - 在循环中反应谷歌地图唯一键错误
问题描述
我得到了这个正在工作的 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
希望有人知道问题是什么。
解决方案
看起来您正在为<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>
推荐阅读
- jupyter - Jupyterlab:是否可以根据元数据标签更改单元格颜色?
- tensorflow - 如何使用 tf.data.TextLineDataset() 将 AWS S3 中的文件加载到 Tensorflow 模型中
- c - C - Memncpy/Strncpy(也尝试过 strncat)复制的字符少于应有的 1 个字符,不胜感激
- c++ - 从使用 tbb 的 C++ 项目构建 DLL 时出现错误 C2711
- d - 使用 -betterC 在 DMD 下创建结构数组时未定义对“_memset64”的引用
- php - 谷歌地图上颤动应用程序上的动态标记
- sql - 执行聚合函数时如何检索其他列?
- c# - 使用 c# 限制对文件夹的访问
- java - 如何在没有注释的情况下使用 Spring Data JDBC?
- javascript - 酶,测试一个使用useContext hook的react组件?