reactjs - 在 react.js 的 componentDidMount() 中执行提取之前,如何通过 navigator.geolocation 获取用户的位置?

标签 reactjs geolocation fetch es6-promise react-lifecycle

我已经尝试了各种不同的方法,但我被难住了。使用 Promise 和在 React 中进行 api 调用的新手。这就是我目前所拥有的:

import React, { Component } from 'react'
import Column from './Column'
import { CardGroup } from 'reactstrap';

let api = "https://fcc-weather-api.glitch.me/api/current?";


class App extends Component {

    constructor(props) {
        super(props)
        this.state = {
            isLoaded: false,
            items: {},
        }

    this.fetchWeather = this.fetchWeather.bind(this)
}

fetchWeather(apiStr) {
    fetch(apiStr)
        .then(res => res.json())
        .then(

            (result) => {

                console.log(result)
                this.setState({
                    isLoaded: true,
                    items: result.main
                });
                console.log(this.state);
            },
            // Note: it's important to handle errors here
            // instead of a catch() block so that we don't swallow
            // exceptions from actual bugs in components.
            (error) => {
                this.setState({
                    isLoaded: true,
                    error
                });
            }
        )

}

componentDidMount() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            api += `lat=${position.coords.latitude}&lon=${position.coords.longitude}`;     
        })
        this.fetchWeather(api);
    }
}

现在正在获取当前位置之前执行 api 调用。我尝试了各种方法,但在获取执行之前无法访问当前位置。处理这个问题的最佳方法是什么?对此的任何见解将不胜感激。有任何问题,请告诉我。谢谢。

最佳答案

由于获取位置是通过回调完成的,因此您必须在回调中获取

navigator.geolocation.getCurrentPosition((position) => {
  api += `lat=${position.coords.latitude}&lon=${position.coords.longitude}`;
  this.fetchWeather(api);
});

关于reactjs - 在 react.js 的 componentDidMount() 中执行提取之前,如何通过 navigator.geolocation 获取用户的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51952341/

相关文章:

javascript - 将组件的状态分配给 React.js 中的变量

javascript - 使 SVG Circle 笔划-dashoffset 动画

javascript - 使用 Meteor(即网络应用程序登陆页面)在 Google PageSpeed Insights 上获得 100 分

android - 如果我已经有 ACCESS_FINE_LOCATION,我可以省略 ACCESS_COARSE_LOCATION 吗?

python - 如何使用 google-maps-services-python 按地点 id 反转地理编码位置

ios - 使用PHCachingImageManager无法获取iPhone的所有视频

reactjs - React Router V6 与 { BrowserRouter, Routes, Route } 路由不起作用,抛出空白页面

python - 如何使用 tweepy 验证推文是否地理定位/接受坐标

javascript - 如果我只想获取 HTML 格式的流,输入 `file.stream()` 与 `response.body` 有什么区别?

php - 多个 while 循环无法正常工作