繁体   English   中英

如何在不返回“未定义”的情况下拉出嵌套的 state object

[英]How do I pull a nested state object without it returning as “undefined”

我继续为我认为很容易完成的事情而奋斗。 我第一次尝试这个时我使用了 React Hooks,但这次我切换回基于 class 的组件只是因为我认为它会出于某种原因改变一些东西。

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,你没有定义,因为this.state.weather包含一个名为weather的元素,所以如果你想访问你的 object,你必须写this.state.weather.weather But there is another problem: if you want to get lat from coord you cannot write this.state.weather.weather.coord.lat because this.state.weather.weather.coord is a string, not a JSON object. 而且你不能做像JSON.parse(this.state.weather.weather.coord)这样的事情,因为它不是有效的 JSON。 因此,我们必须使用字符串,最后,要从coord中获取lat ,您可以这样做:

this.state.weather.weather.coord.split(',')[0].split(':')[1]

render function 在您安装组件的最开始执行。 每次您的 state 更改时,都会再次执行render function。 在其他情况下组件可能会呈现(例如,道具更改)。

您的组件第一次渲染时,您的 state 是

state = {
    weather: {},
    loading: false
  }

但是在您的render function 中,您可以

 <h1>Testing this stuff {this.state.weather.coord.lat} </h1>

这是因为此时您还没有加载weather信息。 您的render组件应该考虑到这一点。 例如,你可以做类似的事情

{ this.state.weather.coord ? <h1>Testing this stuff {this.state.weather.coord.lat}</h1> : <h1>Loading weather data...</h1>}

这样,在加载天气数据之前,您会看到文本“正在加载...”。 你也可以做一些更复杂的事情,比如展示一个微调器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM