0

应用程序.js 文件

const App = () => {
  const [places, setPlaces] = useState([]);

  const [coordinates, setCoordinates] = useState({ lat: 0, lng: 0 });
  const [bounds, setBounds] = useState(null);

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(
      ({ coords: { latitude, longitude } }) => {
        setCoordinates({ lat: latitude, lng: longitude });
        console.log(coordinates, bounds);
      }
    );
  }, []);

useEffect(() => {
    // call to api to fetch data
    // getPlacesData()
    // .then((data) => {
    //   console.table(data);
    //   setPlaces(data);
    // });
    console.log(coordinates, bounds);
  }, [coordinates, bounds]);

这个组件正在返回这个——

<>
  <CssBaseline />
  <Header />
  <Grid container spacing={3} style={{ width: "100%" }}>
    <Grid item xs={12} md={4}>
      <List />
    </Grid>
    <Grid item xs={12} md={8}>
      <Map
        setCoordinates={setCoordinates}
        setBounds={setBounds}
        coordinates={coordinates}
      />
    </Grid>
  </Grid>
</>

Map.jsx 文件

const Map = ({ setCoordinates, setBounds, coordinates }) => {
  const classes = useStyles();
  const isMobile = useMediaQuery("(min-width:600px)");

  return (
    <div className={classes.mapContainer}>
      <GoogleMapReact
        bootstrapURLKeys={{ key: API_KEY }}
        defaultCenter={coordinates}
        center={coordinates}
        defaultZoom={14}
        margin={[50, 50, 50, 50]}
        options={""}
        onChange={(e) => {
          // console.log(e);
          setCoordinates({ lat: e.center.lat, lng: e.center.lng });
          setBounds({ ne: e.marginBounds.ne, sw: e.marginBounds.sw });
        }}
        onChildClick={""}
      ></GoogleMapReact>
    </div>
  );
};

当第一次构建代码时,这个工作正常地图显示我的位置但是当我刷新它时,坐标设置为 {lat: 0, lng: 0}

当我在构建后第一次运行代码时,开发者控制台输出:(此输出仅在代码构建后显示一次)</p>

App.js:37 
{lat: 0, lng: 0}
null

App.js:37 
{lat: 0, lng: 0}
null

App.js:37 
{lat: 0, lng: 0}
{ne: {…}, sw: {…}}

App.js:37 
{lat: *CORRECT_ONE*, lng: *CORRECT_ONE*}
{ne: {…}, sw: {…}}

App.js:25 
{lat: 0, lng: 0}
null

App.js:37 
{lat: *CORRECT_ONE*, lng: *CORRECT_ONE*}
{ne: {…}, sw: {…}}

App.js:37 
{lat: *CORRECT_ONE* , lng: *CORRECT_ONE*}
{ne: {…}, sw: {…}}


当我刷新选项卡并再次运行它时

App.js:37
{lat: 0, lng: 0}
 null
App.js:37 
{lat: 28.7123711, lng: 77.1176437}
 null
App.js:25 
{lat: 0, lng: 0}
 null
App.js:37 
{lat: 0, lng: 0}
 null
App.js:37 
{lat: 0, lng: 0}
 
{ne: {…}, sw: {…}}
ne: {lat: 0.010128021187483682, lng: 0.03325939178466797}
sw: {lat: -0.010128021187483682, lng: -0.03325939178466797}
[[Prototype]]: Object
4

0 回答 0