首页 > 解决方案 > React; accessing fields within an Object

问题描述

this is my first question, i hope this is ok: i am learning about react, and currently am trying to extract weather data from an API. I can save the data in a state without problems, and can access the first object layer without problems too. But the data i need is in the thirs layer (data -> main -> temp), and i get an undefined error when trying to access main.temp

showing "main" on the consoles gives me this: 
humidity: 87
pressure: 1017
temp: 285.81
temp_max: 287.04
temp_min: 284.26

but I somehow cannot access the fields within. Here is my code that still works:

import React from "react";
import axios from "axios";

class alex extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      daten: []
    };
    this.tempConverter = this.tempConverter.bind(this);
  }

  componentDidMount() {
    axios
      .get(
        `https://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=436238e5e5563aff959aff1d8acc8e32`
      )
      .then(res => {
        this.setState({ daten: res.data });
      });
  }

  tempConverter() {
    const data = this.state.daten.main;
    console.log(data);
  }

  render() {
    return <div>Current Temperatur: {this.tempConverter()}</div>;
  }
}

export default alex;

when trying to access data.temp in the convertTemp() function i get TypeError: Cannot read property 'temp' of undefined

Thank you very much for your help.

标签: javascriptreactjs

解决方案


Your daten property in state is initialized to empty array, there is not any property main. Maybe after you get the response from async call. But for the first render is it just empty array.


推荐阅读