【问题标题】:How do I get user's location via navigator.geolocation before my fetch executes in componentDidMount() in react.js?如何在我的 fetch 在 react.js 的 componentDidMount() 中执行之前通过 navigator.geolocation 获取用户的位置?
【发布时间】:2018-08-21 15:45:10
【问题描述】:

我已经尝试了多种不同的方法,但都被难住了。在 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);
    }
}

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

【问题讨论】:

    标签: reactjs geolocation fetch es6-promise react-lifecycle


    【解决方案1】:

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

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

    【讨论】:

    • 当我这样做时,我会在this.fetchWeather(api) 收到Uncaught TypeError: Cannot read property 'fetchWeather' of null
    • @AlexKramer 抱歉没有看到您使用的功能。要编辑。箭头函数允许您使用 this 关键字而不绑定它
    【解决方案2】:

    使用usePosition()之类的钩子和函数组件怎么样?

    在这种情况下,检测到浏览器位置后获取数据的任务可能如下所示:

    import React, { useEffect } from 'react';
    import { usePosition } from 'use-position';
    
    export const Weather = () => {
      const { latitude, longitude, error } = usePosition();
    
      useEffect(() => {
        if (latitude && longitude && !error) {
          // Fetch weather data here.
        }
      }, []);
    
      return <div>Render weather data here</div>;
    };
    

    当然不要忘记使用npm 安装自定义挂钩:

    npm i use-position --save
    

    或使用yarn:

    yarn add use-position
    

    【讨论】:

    猜你喜欢
    • 2018-06-05
    • 1970-01-01
    • 2011-06-13
    • 2018-03-16
    • 2020-11-14
    • 1970-01-01
    • 2017-01-12
    • 2021-07-24
    相关资源
    最近更新 更多