在react.js中的ComponentDidmount()中执行FETCH之前,如何通过Navigator.geolocation获取用户的位置? [英] How do I get user's location via navigator.geolocation before my fetch executes in componentDidMount() in react.js?

查看:0
本文介绍了在react.js中的ComponentDidmount()中执行FETCH之前,如何通过Navigator.geolocation获取用户的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了各种不同的方法,但都被难住了。在Reaction中使用承诺和进行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调用正在执行。我尝试了各种方法,但未能在FETCH执行之前访问当前位置。处理这件事最好的办法是什么?任何关于这方面的见解都将受到衷心的赞赏。有任何问题,请让我知道。谢谢。

推荐答案

因为获取位置是通过回调完成的,所以您必须在回调中获取

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

这篇关于在react.js中的ComponentDidmount()中执行FETCH之前,如何通过Navigator.geolocation获取用户的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆