javascript - 无法在子组件中读取包含对象数组的道具
问题描述
我正在尝试在地图中显示多个标记。
我在父组件中有这段代码:
const [coords, setCoords] = useState ([{}])
setCoords(
[
{lat: -5.2119899, lng: 119.4461816},
{lat: -5.209704, lng: 119.44075},
]
)
<ReactGoogleMaps coordinates={coords} />
子组件中的代码片段:
const WrappedMap = withScriptjs(withGoogleMap((props) =>
<GoogleMap
defaultZoom={13}
defaultCenter={{ lat: Number(props.coordinates.lat), lng: Number(props.coordinates.lng) }}
>
{props.isMarkerShown && <Marker position={{ lat: Number(props.coordinates.lat), lng: Number(props.coordinates.lng)}} />}
</GoogleMap>
));
function ReactGoogleMaps(props) {
return (
<div style={{width: "100%", height: "100%"}}>
<WrappedMap
coordinates={{lat: props.coordinates[0].lat, lng: props.coordinates[0].lng}}
/>
</div>
)
};
上面的代码运行良好。问题是当坐标道具的索引从0更改为1时,它会返回此错误:TypeError: Cannot read property 'lat' of undefined
。
我已经坚持了几天了。如果有人可以帮助我,我将不胜感激。非常感谢你。
解决方案
当第一次渲染发生时,不会立即设置坐标ReactGoogleMaps
。因此,当您尝试访问 props.coordinates[0] 的纬度时,您会收到此未定义的错误。
我建议:
- 在 coords.length > 0 之前不渲染 ReactGoogleMaps
- 在尝试访问之前检查第一个元素的存在,如下所示:
function ReactGoogleMaps(props) {
return (
<div style={{width: "100%", height: "100%"}}>
{ props.coordinates[0] &&
<WrappedMap
coordinates={{lat: props.coordinates[0].lat, lng: props.coordinates[0].lng}}
/>
}
</div>
)
};
推荐阅读
- java - 使用AuthenticationProvider登录时如何设置cookie过期时间
- cookiecutter-django - 升级 Django 版本
- sql-server - SQL Server 几乎重复的索引 - 删除哪一个
- reactjs - 在反应中,如何解决字符串被转换为对象的问题?
- javascript - React Redux - 仅当前一个路由与新路由相同时才在 useEffect 中调度操作
- caching - 如何将分页系统(按需分页)视为另一层缓存?
- android - 运行时无法执行颤振应用程序
- docker - 气流的 entrypoint.sh 文件中 TRY_LOOP="20" 的目的是什么?
- python-3.x - 有没有办法在使用 Django Graphene 制作的 GraphQL API 中检索枚举描述而不是名称
- python - discord.py 你能从 discord 标签中获取用户对象吗?