setState不适用

时间:2019-12-18 01:03:18

标签: reactjs geolocation

状态值通常在位置功能中显示。 然而 经度和纬度在API JSON中显示为“ 0”。 我该如何解决?

    this.state = {
      lat: 0,
      lon: 0
    };

  getPosition = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        position => {
          this.setState({
            lat: position.coords.latitude,
            lon: position.coords.longitude
          });
          console.log(this.state);
        },
        error => {
          console.log(error);
        }
      );
    }
    this.getWeather();
  };

  getWeather = async () => {
    const { lat, lon } = this.state;
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${App_Id}`;
    await Axios.get(url)
      .then(res => res.data)
      .then(data => console.log(data));
  };

  componentDidMount() {
    this.getPosition();
  }

enter image description here

0 个答案:

没有答案