【问题标题】:React TypeError undefined反应类型错误未定义
【发布时间】:2019-07-30 20:03:42
【问题描述】:

我是 React 世界的新手。我正在创建天气应用程序,并且正在使用 openweathermap api 来获取数据(使用了暗夜 api 并且遇到了同样的问题)。 问题是我得到一个获取数据并将其保存到状态。我可以通过 JSX 和 console.log 打印该状态的全部内容,但无法访问内部的特定数据(通过 console.log 和 JSX)。 问题说: TypeError: Cannot read property 'city' of undefined

这是我的代码:

import React from 'react';
import TemperaturesList from './TemperaturesList';
import axios from 'axios';

class WeatherData extends React.Component {
    state = { weatherData: {}, error: null };

    componentDidMount(){

        axios.get('https://samples.openweathermap.org/data/2.5/forecast?lat=${this.props.lat}&lon=${this.props.long}&appid=MYAPPID')
        .then(result => this.setState({
            weatherData: result
        }))
        .catch(error => this.setState({
            error: error
        }))

    }



    render(){
        return(
            <div>
            {JSON.stringify(this.state.weatherData)} // this works
            <h3>Current weather:</h3>
            {JSON.stringify(this.state.weatherData.data.city)} // this does not work
            </div>

        );
    };
};

export default WeatherData;

这是我从状态中获取和保存的结果:

【问题讨论】:

    标签: javascript reactjs api typeerror


    【解决方案1】:

    API 调用将在 render 之后触发,因此 this.state.weatherData.data 在初始渲染时将未定义。此外,最好将 axios response.data 存储在状态而不是整个响应本身。这应该工作

    import React from 'react';
    import TemperaturesList from './TemperaturesList';
    import axios from 'axios';
    
    class WeatherData extends React.Component {
      state = { weatherData: {city: ''}, error: null };
    
      componentDidMount(){
        axios.get('https://samples.openweathermap.org/data/2.5/forecast? 
         lat=${this.props.lat}&lon=${this.props.long}&appid=MYAPPID')
        .then(result => this.setState({
            weatherData: result.data
        }))
        .catch(error => this.setState({
            error: error
        }))
    
    }
    
    render(){
        return(
            <div>
            {JSON.stringify(this.state.weatherData)}
            <h3>Current weather:</h3>
            {JSON.stringify(this.state.weatherData.data.city)}
            </div>
    
        );
     };
     };
    
     export default WeatherData;
    

    【讨论】:

    • 谢谢!很有帮助!
    【解决方案2】:

    componentDidMount从服务器获取数据之前,React 会尝试渲染当前的状态:

    state = { weatherData: {}, error: null };
    ....
    {JSON.stringify(this.state.weatherData.data.city)}
    

    此时weatherData 是一个空对象。

    您可以通过在状态中设置data 来修复它:

    state = { weatherData: { data: {} }, error: null };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2019-10-31
      • 2017-09-01
      • 2016-08-07
      • 2019-01-07
      • 2020-01-28
      • 2021-10-24
      相关资源
      最近更新 更多