Openweather API JSON数据

时间:2019-02-26 19:59:12

标签: reactjs redux react-redux openweathermap

我从openweathermap接收到JSON数据时遇到问题。可能我没有看到数组或其他东西,但是我需要帮助。

import React, { Component } from 'react';
import { connect } from 'react-redux';

class Weather extends Component {

render() {
    const weatherData = this.props.weather;
    console.log(weatherData);
    return (
        <div>
            <div>{weatherData.name}</div>
            <div>Temperature: {weatherData.main.temp}</div>
        </div>
    );
}
}

const mapStateToProps = (state) => {
    return {
        weather: state.weather
    };
};
export default connect(mapStateToProps)(Weather);

控制台错误:

TypeError: Cannot read property 'temp' of undefined

这个对象是从openweathermap API接收的

    {
  "coord": {
    "lon": -0.13,
    "lat": 51.51
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 282.96,
    "pressure": 1030,
    "humidity": 71,
    "temp_min": 280.15,
    "temp_max": 286.15
  },
  "visibility": 10000,
  "wind": {
    "speed": 3.1,
    "deg": 70
  },
  "clouds": {
    "all": 0
  },
  "dt": 1551209222,
  "sys": {
    "type": 1,
    "id": 1414,
    "message": 0.0082,
    "country": "GB",
    "sunrise": 1551163869,
    "sunset": 1551202579
  },
  "id": 2643743,
  "name": "London",
  "cod": 200
}

例如,我正在获取weatherData.name,没有任何问题,但是weatherData.main.temp导致了错误

console.log(weatherData) console.log(weatherData)

0 个答案:

没有答案