首页 > 解决方案 > 如何拉出嵌套状态对象而不返回“未定义”

问题描述

我继续为我认为很容易完成的事情而奋斗。第一次尝试时我使用了 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
}

标签: javascriptreactjs

解决方案


Ciao,你得到了 undefined 因为this.state.weather包含一个名为weatherso 如果你想访问你的对象你必须写的元素this.state.weather.weather。但是还有另一个问题:如果你想从中获取latcoord你不能写this.state.weather.weather.coord.lat,因为this.state.weather.weather.coord它是一个字符串,而不是一个 JSON 对象。而且你不能做任何事情,JSON.parse(this.state.weather.weather.coord)因为它不是一个有效的 JSON。所以,我们必须使用字符串,最后,latcoord可以这样做:

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

推荐阅读