反应 setState 未定义?

React setState is undefined?

我有一个从浏览器导航器功能到天气的简单获取位置 api。我不明白为什么纬度和经度的两个控制台都有效,但是当我设置状态时它对我大喊大叫说未捕获 TypeError: Cannot read property 'setState' of undefined.

为了更清楚这两个控制台我得到了位置

console.log(position.coords.latitude)
console.log(position.coords.longitude)

但这就是说不能将未定义的东西传递给 setState

this.setState({lat:position.coords.latitude,lon:position.coords.longitude})

import React from 'react';
import axios from 'axios';
import WeatherGadget from './weather.component'

export default class WeatherApi extends React.Component {
    constructor(props) {
        super(props);
        this.state = { city: null,lat:0,lon:0,wind:0,weather:0,icon:null };
      }

    componentDidMount() {
       const location = ()=>{navigator.geolocation.getCurrentPosition(function(position) {
           console.log(position.coords.latitude)
           console.log(position.coords.longitude)
            this.setState({lat:position.coords.latitude,lon:position.coords.longitude})          
            //Uncaught TypeError: Cannot read property 'setState' of undefined
      
        })}
        location();


            const url = `https://api.openweathermap.org/data/2.5/onecall?lat=${this.state.lat}&lon=${this.state.lon}&appid=8821HIDDEN4e9d78`;

            const getWeather = async ()=>{
                let res = await axios.get(url)
                const  weatherObj = res.data;
                console.log("===",weatherObj)

                const currentWeather = weatherObj.current.temp
                const windSpeed = weatherObj.current.wind_speed
                const icon = weatherObj.current.weather[0].icon
                this.setState({wind:windSpeed,weather:currentWeather,icon:icon})
            }
            getWeather()

      
    }  

    render() {
        return (

            <div >
            <WeatherGadget city={this.state.city}  wind ={this.state.wind} weather={this.state.weather} icon={this.state.icon}/>
            </div>
        )
    }
}

在导航器对象中很简单,你不能访问这个对象,因为它引用了 window 对象所以为此我在 promise 中使用导航器对象,如果导航器给我纬度和经度,那么我解决我的问题promise if not reject the promise 和 return the promise .

ComponentDidMount 中,我使用 await 调用了该函数,因为它 return 我得到了 promise 之后我就有了价值,然后我设置了状态

并调用了另一个 getWeather 函数

import React from "react";
import axios from "axios";
// import WeatherGadget from './weather.component'

export default class WeatherApi extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      city: null,
      lat: 0,
      lon: 0,
      wind: 0,
      weather: 0,
      icon: null
    };
  }


  async componentDidMount() {
    const location = await this.location();
    location && this.setState({ lat: location.lat, lon: location.long });
    location && this.getWeather();
  }
  location = () => {
   //return the promise that contain the navigator object
    return new Promise((resolve, reject) => {
      try {
        navigator.geolocation.getCurrentPosition(position => {
          resolve({
            lat: position.coords.latitude,
            long: position.coords.longitude
          });
        });
      } catch (error) {
        let temp = {
          lat: 24.8607,
          long: 67.0011
        };
        reject(temp);
      }
    });
  };
//calling weather api
  getWeather = async () => {
    const url = `https://api.openweathermap.org/data/2.5/onecall?lat=${
      this.state.lat
    }&lon=${this.state.lon}&appid=8821HIDDEN4e9d78`;
    console.log("url", url);
    try {
      const res = await axios.get(url);
      if (res) {
        console.log("res", res.data)
        const weatherObj = res.data;
        console.log("===", weatherObj);
        const currentWeather = weatherObj.current.temp;
        const windSpeed = weatherObj.current.wind_speed;
        const icon = weatherObj.current.weather[0].icon;
        this.setState({ wind: windSpeed, weather: currentWeather, icon: icon });
      }
    } catch (error) {
      console.log("error", error)
    }
  };
  render() {
    return (
      <div>
        {/* <WeatherGadget city={this.state.city}  wind ={this.state.wind} weather={this.state.weather} icon={this.state.icon}/> */}
        <p> Lat: {this.state.lat}</p>
        <p> Lng: {this.state.lon}</p>
        <p> Weather: {this.state.weather}</p>
        <p>Wind: {this.state.wind}</p>

      </div>
    );
  }
}

我只需要在组件安装外部创建函数,然后在内部简单地调用它,如下所示

import React from 'react';
import axios from 'axios';
import WeatherGadget from './weather.component'

export default class WeatherApi extends React.Component {
    constructor(props) {
        super(props);
        this.state = { city: null, lat: 0, lon: 0, wind: 0, weather: 0, icon: null };
    }
    location = () => {
        navigator.geolocation.getCurrentPosition((position) => {
            this.setState({ lat: position.coords.latitude, lon: position.coords.longitude })
            //Uncaught TypeError: Cannot read property 'setState' of undefined

            const url = `https://api.openweathermap.org/data/2.5/onecall?lat=${this.state.lat}&lon=${this.state.lon}&appid=8821a871fa3513caf66ad2e8ab4e9d78`;
            console.log("====url", url)

            const getWeather = async () => {
                let res = await axios.get(url)
                const weatherObj = res.data;
                console.log("===", weatherObj)

                const currentWeather = weatherObj.current.temp
                const windSpeed = weatherObj.current.wind_speed
                const icon = weatherObj.current.weather[0].icon
                this.setState({ wind: windSpeed, weather: currentWeather, icon: icon })
            }
            getWeather()

        })
    }

     componentDidMount() {

         this.location();
    }

    render() {
        return (

            <div >
                <WeatherGadget city={this.state.city} wind={this.state.wind} weather={this.state.weather} icon={this.state.icon} />
            </div>
        )
    }
}