简体   繁体   English

反应类型错误未定义

[英]React TypeError undefined

I'm new in React world.我是 React 世界的新手。 I'm creating weather app and I'm using openweathermap api to get data (used dark sky api and had the same problem).我正在创建天气应用程序,我正在使用 openweathermap api 来获取数据(使用了黑暗的天空 api 并遇到了同样的问题)。 The problem is that I get a fetch data and save it to state.问题是我获取了一个获取数据并将其保存到状态。 I am able to print by JSX and console.log the whole content of that state but can't reach specific data inside (by console.log and JSX).我可以通过 JSX 和 console.log 打印该状态的全部内容,但无法访问内部的特定数据(通过 console.log 和 JSX)。 The problem says: TypeError: Cannot read property 'city' of undefined问题说: TypeError:无法读取未定义的属性“城市”

Here's my code:这是我的代码:

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;

And here's what I get from fetch and save in state:这是我从 fetch 和 save in state 中得到的:

在此处输入图片说明

Before the data is being fetched from the server in componentDidMount React will try to render what is currently in the state:componentDidMount从服务器获取数据之前,React 将尝试呈现当前处于状态的内容:

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

where weatherData is an empty object at this point.此时, weatherData是一个空对象。

You could fix it by setting data in the state:您可以通过在状态中设置data来修复它:

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

The api call will be triggered after render and hence this.state.weatherData.data will be undefined on initial render. api 调用将在render后触发,因此this.state.weatherData.data在初始渲染时将是未定义的。 Also it is better to store the axios response.data in state rather than the whole response itself.此外,最好将 axios response.data存储在状态而不是整个响应本身。 This should work这应该工作

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;

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

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