leaflet - 发送我的本地位置传单的问题
问题描述
当我初始化 const 时,就像
-lat 和 leg 仅在函数内部可用,当我将它们发送到地图时(我正在使用 Leaflet)它没有显示它们并且它给了我那个错误:
错误:重新渲染过多。React 限制了渲染的数量以防止无限循环。
import {Component,useState,useEffect,useRef, ReactNode, CSSProperties, Link} from 'react';
import { MapContainer, TileLayer, Marker, Popup,useLeaflet,leafletElement} from 'react-leaflet'
function HomePage(){
const [lat, setLat] = useState(null);
const [lng, setLng] = useState(null);
const [status, setStatus] = useState(null);
if (!navigator.geolocation) {
setStatus('Geolocation is not supported by your browser');
} else {
setStatus('Locating...');
navigator.geolocation.getCurrentPosition((position) => {
setStatus(null);
setLat(position.coords.latitude);
setLng(position.coords.longitude);
console.log(lat,lng)
}, () => {
setStatus('Unable to retrieve your location');
});
}
const position = [lat,lng]
return(
<MapContainer center={position} zoom={13} scrollWheelZoom={false}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
)};
export default HomePage
解决方案
您的组件不断地重新渲染。我不确定,但我认为下面应该可以工作。您必须使用useEffect
钩子并在组件开头添加对导航器的检查if(!navigator.geolocation) { return null; }
推荐阅读
- python - 在 Microsoft Graph 中获取用户个人资料图片
- python - 图例未显示 matplotlib.patches
- r - 在 R 中重命名列名
- openlayers - 如何通过单击其内部空间来选择多边形
- angular - 如何自动导航 ngu 轮播点
- php - 在 php 中使用 curl 发送摘要身份验证请求时出现错误请求 400 错误
- google-apps-script - 如何在另一个电子表格中使用 Google Apps 脚本?
- python-2.7 - 我正在尝试制作端口扫描仪
- java - 尝试在导航标题部分添加横幅广告后,应用程序崩溃
- php - 两个表一个包含记录,第二个包含位置我想显示第一个表记录而不连接