首页 > 解决方案 > 发送我的本地位置传单的问题

问题描述

当我初始化 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='&copy; <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

标签: leafletgps

解决方案


您的组件不断地重新渲染。我不确定,但我认为下面应该可以工作。您必须使用useEffect钩子并在组件开头添加对导航器的检查if(!navigator.geolocation) { return null; }


推荐阅读