简体   繁体   English

反应位置返回未定义

[英]React Location returns undefined

I'm trying to get the user location for a weather app but the log return undefined我正在尝试获取天气应用程序的用户位置,但日志返回未定义

 const [lat, setLat] = useState(); const [long, setLong] = useState(); useEffect(() => { const handleLocation = () => { navigator.geolocation.getCurrentPosition((position) => { setLat(position.coords.latitude); setLong(position.coords.longitude); }); console.log(lat); console.log(long); }; if (navigator.geolocation) { navigator.permissions.query({ name: 'geolocation' }).then(function (result) { if (result.state === 'granted') { console.log(result.state); handleLocation(); } else if (result.state === 'prompt') { console.log('prompt'); } else if (result.state === 'denied') { console.log('Denied'); } }); } }, [lat, long]);

I get the log granted confirming that the browser granted the location but then I get undefined for the lat and long我获得了日志,确认浏览器授予了该位置,但随后我得到了纬度和经度的未定义

I believe this is a simple async problem.我相信这是一个简单的异步问题。 The navigator.geolocation.getCurrentPosition is asynchronous and will not call the given function straight away. navigator.geolocation.getCurrentPosition是异步的,不会立即调用给定的 function。

I believe if you move your console.log inside the callback, then the state should have the right value.我相信如果你在回调中移动你的console.log ,那么 state 应该有正确的值。

const handleLocation = () => {
  navigator.geolocation.getCurrentPosition((position) => {
    setLat(position.coords.latitude);
    setLong(position.coords.longitude);
    console.log(lat);
    console.log(long);
  });
};

Also bear in mind that React state updates can be asynchronous.还要记住,React state 更新可以是异步的。 A better way to test the different values of the lat and long variables, would be to log them in the render function.测试latlong变量的不同值的更好方法是将它们log在渲染 function 中。

function Component() {
    const [lat, setLat] = useState()

    useEffect( /* your useEffect callback here */);

    console.log(lat); // you will see all the values of lat through time now
}

Found the error being the OS blocking the location service from the browser发现错误是操作系统阻止了浏览器的定位服务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM