javascript - 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.
解决方案
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.
推荐阅读
- apache-spark - 为了避免手动文件错误,如何在 spark/scala 中编码列检查的动态数据类型
- css - 使用 Recharts 实现循环进度条
- asp.net - xml to json 将所有数据类型转换为字符串,有没有办法强制元素上的数据类型(.net)
- php - 从 laravel 控制器接收的数据未更新为 vue 变量
- php - 在模型中添加语法“where”,但未选中(datatables ajax codeigniter)
- verilog - 错误:在 verilog 中实现宏时出现不匹配的字符 (')
- dart - 颤振垂直抽屉
- java - 如何获取文本框的字符串值
- angular - angular 6 中的 owl-date-time 选择器从输入中删除时间
- dart - 多个容器相互叠加并在它们之间导航