javascript - 如何拉出嵌套状态对象而不返回“未定义”
问题描述
我继续为我认为很容易完成的事情而奋斗。第一次尝试时我使用了 React Hooks,但这次我切换回基于类的组件只是因为我认为它会出于某种原因改变一些东西。
import React, { Component } from 'react'
import Search from './components/layout/Search'
import axios from 'axios'
class App extends Component {
state = {
weather: {},
loading: false
}
sendUp = async (state) => {
this.setState({loading: true});
const res = await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=${state}&appid={api key hidden for post.}`)
this.setState({weather: res.data})
this.setState({loading: false})
}
render() {
return (
<React.Fragment>
<div className="container">
<Search sendUp={this.sendUp} />
<h1>Testing this stuff {this.state.weather.coord.lat} </h1>
</div>
</React.Fragment>
)
}
}
export default App
希望我的困惑是有道理的。我认为就像这样拉日期一样简单:{this.state.weather.coord.lat}。但是,我收到此错误。无法读取未定义的属性“纬度”。我只是错过了某种基本的 javascript 基础,还是在使用 React 库时调用嵌套对象不同?
{
"weather": {
"coord": "{lat: 32.88, lon: -111.76}",
"weather": "[{…}]",
"base": "stations",
"main": "{feels_like: 311.12, humidity: 32, pressure: 1012, …}",
"visibility": 10000,
"wind": "{deg: 330, speed: 3.6}",
"clouds": "{all: 1}",
"dt": 1595714117,
"sys": "{country: \"US\", id: 3616, sunrise: 1595680572, suns…}",
"timezone": -25200,
"id": 5288636,
"name": "Casa Grande",
"cod": 200
},
"loading": false
}
解决方案
Ciao,你得到了 undefined 因为this.state.weather
包含一个名为weather
so 如果你想访问你的对象你必须写的元素this.state.weather.weather
。但是还有另一个问题:如果你想从中获取lat
,coord
你不能写this.state.weather.weather.coord.lat
,因为this.state.weather.weather.coord
它是一个字符串,而不是一个 JSON 对象。而且你不能做任何事情,JSON.parse(this.state.weather.weather.coord)
因为它不是一个有效的 JSON。所以,我们必须使用字符串,最后,lat
你coord
可以这样做:
this.state.weather.weather.coord.split(',')[0].split(':')[1]
推荐阅读
- java - Spring Boot 覆盖测试中的应用程序属性
- regex - 正则表达式未找到两个匹配项
- python - 在 python 中使用 `with` 运算符读取文件时出现问题
- c++ - 如何根据需要安排哈希?
- python - 尝试将数据拆分为测试和验证集时出现张量断言错误?
- python - 将感兴趣区域提取为单独的图像
- jinja2 - 在 dbt 的 Jinja 宏中使用字符串作为参数
- javascript - 合并两个对象以获得与第一个对象具有相同结构的另一个对象
- python - 从列表中删除整数后,如何防止python在迭代期间跳过整数?
- django - 如何通过 Heroku 部署分离的 Django 前端和后端?