【问题标题】:Can't store navigator.geolocation data in useffect, with a usestateCan't store navigator.geolocation data in useffect, with a usestate
【发布时间】:2020-11-26 21:04:13
【问题描述】:

我有一个问题,我想在渲染之前将navigator.geolocation 的纬度和经度存储在useEffect 中,使用一个空数组,但是当我console.log 我的结果时它显示null

这里是相关部分。

import React, {useState, useEffect} from 'react';

const [userPos, setUserPos] = useState({lat: null, long: null})

 useEffect(() => {
      navigator.geolocation.getcurrentposition((pos) =>{
          console.log(pos.coords.latitude + " " + pos.coords.longitude) // display VALUE
          setUserPos({ 
                lat: pos.coords.latitude,
                long: pos.coords.longitude,
           }) // store data in usestate
          console.log(userPos) // Display Null
     }, (err) => {
          console.log(err);
     },options);
    }
  })
 }, [])

那么为什么,当我在useEffect 中记录pos.coords 时,我有值,但在我记录状态时却没有。有什么想法吗?

【问题讨论】:

  • 因为 react 不会在中途重新渲染你的钩子。当函数完成后状态发生变化时,它会重新渲染。
  • @Dominik 以及如何在第一次渲染中存储数据
  • 我为你添加了答案

标签: reactjs geolocation react-hooks use-effect use-state


【解决方案1】:

React 不能在中途重新渲染你的函数。而是创建一个新变量,然后将其传递给 set 函数并使用它。请注意,在重新渲染后,userPos 将在 useEffect 之外提供给您。因此,新变量仅在同一 useEffect 函数中对您有用。

import React, {useState, useEffect} from 'react';

const [userPos, setUserPos] = useState({lat: null, long: null})

 useEffect(() => {
      navigator.geolocation.getcurrentposition((pos) =>{
          console.log(pos.coords.latitude + " " + pos.coords.longitude) // display VALUE
          const newUserPos = { 
                lat: pos.coords.latitude,
                long: pos.coords.longitude,
           };
          setUserPos(newUserPos) // store data in usestate
          console.log(newUserPos) // Display your values
     }, (err) => {
          console.log(err);
     },options);
    }
  })
 }, [])

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2021-11-12
    • 2022-12-02
    • 2021-10-27
    • 2019-10-05
    • 1970-01-01
    • 2016-11-17
    • 2023-02-17
    • 2017-02-18
    相关资源
    最近更新 更多