【问题标题】:Cant access some of the object properties when using openweathermap api使用 openweathermap api 时无法访问某些对象属性
【发布时间】:2021-04-14 11:37:46
【问题描述】:

我正在使用 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 时,得到错误 Objects are not valid as a React child (found: object with keys {lon, lat})。如果您打算渲染一组子项,请改用数组 但是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

【问题讨论】:

  • 你能不能console.log(response.data)你得到并在这里显示输出。
  • 显示一些代码。
  • 需要更多的上下文才能知道你在说什么。
  • @NikitaGalibin coord: {lon: 76.2711, lat: 10.8505} weather: [{…}] base: "stations" main: {temp: 297.15, feel_like: 301.07, temp_min: 297.15, temp_max: 297.15,压力:1008,...} 能见度:1500 风:{速度:1.03,度:70} 云:{全部:75} dt:1610131334 系统:{类型:1,id:9209,国家:“IN”,日出:1610154958,日落:1610196454} 时区:19800 id:1256432 名称:“Shōranūr” 编码:200
  • 你想在哪里显示它?如果可能,请提供整个组件的代码。

标签: javascript json reactjs object openweathermap


【解决方案1】:

以下是如何显示 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 元素。 对不起,格式化。

【讨论】:

  • 实际上,在尝试显示 data.coord.lon 时,我收到错误消息说“lon”未定义。这就是我没有添加更多 JSX 元素的原因。感谢您的帮助。
  • @Anoop 这意味着您的数据加载不正确。我会修改我的答案,你可以再试一次。
  • 尝试异步运行weatherInit()函数
  • @NikitaGalibin console.log 在 return 语句按预期给出结果之前。这意味着数据加载正确,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-17
  • 1970-01-01
  • 2011-07-05
  • 2013-05-28
  • 2012-05-25
相关资源
最近更新 更多