reactjs 使用openweathermap API时无法访问某些对象属性

cotxawn7  于 2022-12-22  发布在  React
关注(0)|答案(1)|浏览(232)

我正在使用axios从我的react应用程序的openweathermap API中获取天气信息,从api调用的结果(一个json对象)中,我可以访问一些属性,例如data.base,但是不能访问data.coord.icondata.weather[0].id等。

data = [
        coord: { lon: -0.1257,lat: 51.5085},
        weather: [{ id: 721,
                    main: "Haze",
                    description: "haze",
                    icon: "50n"
                  }],
        base: "stations"
      ]

我尝试了所有可能的组合。当尝试返回data.coord时,得到错误对象作为React子对象无效(发现:如果您想要呈现子对象的集合,请改用数组但是data.coord.lon给出了lon of undefined

import React, { Component } from 'react';
import axios from 'axios';

export class WeatherInfo extends Component {

constructor(props) {
    super(props)

    this.state = {
        isFetching: false,
        data: [],
    }
}

//function to fetch weather information
async  getWeatherData(lat, lon) {
    const weatherApi = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${process.env.REACT_APP_WEATHER_KEY}`

    try {
        this.setState({ ...this.state, isFetching: true });
        const response = await axios.get(weatherApi);
        this.setState({ data: response.data, isFetching: false });
        console.log(response.data)
    } catch (error) {
        console.log(error);
        this.setState({ isFetching: false })
    }
}

//function to get access to users location and to call getWeatherData function
weatherInit = () => {

    const success = (position) => {
        this.getWeatherData(position.coords.latitude, position.coords.longitude);
    }

    const error = () => {
        alert('Unable to retrieve location.');
    }

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error);
    } else {
        alert('Your browser does not support location tracking, or permission is denied.');
    }
}

componentDidMount() {
    this.weatherInit();
}

render() {
    const { data } = this.state;
    return (
        <div>
            <p>{data.name}</p>
        </div>
    )
}
}

export default WeatherInfo
dced5bon

dced5bon1#

下面是如何显示API返回的各种数据的示例。

import React, {
  Component
} from 'react';
import axios from 'axios';

export class WeatherInfo extends Component {

  constructor(props) {
    super(props)

    this.state = {
      isFetching: false,
      data: [],
    }
  }

  //function to fetch weather information
  async getWeatherData(lat, lon) {
    const weatherApi = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${process.env.REACT_APP_WEATHER_KEY}`

    try {
      this.setState({ ...this.state,
        isFetching: true
      });
      const response = await axios.get(weatherApi);
      if(response.status===200){
            //update state only if status is 200
            this.setState({
                 data: response.data,
                 isFetching: false
            });
      console.log(response.data)
      }
    } catch (error) {
      console.log(error);
      this.setState({
        isFetching: false
      })
    }
  }

  //function to get access to users location and to call getWeatherData function
  weatherInit = () => {

    const success = (position) => {
      this.getWeatherData(position.coords.latitude, position.coords.longitude);
    }

    const error = () => {
      alert('Unable to retrieve location.');
    }

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(success, error);
    } else {
      alert('Your browser does not support location tracking, or permission is denied.');
    }
  }

  componentDidMount() {
    this.weatherInit();
  }

  render() {
    const {data} = this.state;
    
    if (data) {
      return ( 
      <div >
        //display coord
        <p > {data.coord.lon} < /p> 
        <p > {data.coord.lat} < /p>
        // display weather ids
        {data.weather.map(item => {
           return ( 
           < p > { item.id } < /p>) })
         } 
         < p > { data.name } < /p> < / div >
        )
    }
    else {
     return (<div>Data is loading or Not Found</div>)}
    }
   }
 }

  export default WeatherInfo

您必须为每个要显示的值创建一个JSX元素。抱歉,这是为了格式化。

相关问题