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

Ale*_*mer 3 geolocation fetch reactjs es6-promise react-lifecycle

我已经尝试了各种不同的方法,但我被难住了。在 React 中使用 promise 和进行 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Joã*_*nha 6

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

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