【问题标题】:Error while assigning JSON data to variable and accessing it through the state in React将 JSON 数据分配给变量并通过 React 中的状态访问它时出错
【发布时间】:2016-07-03 19:36:20
【问题描述】:

我最近开始使用 React.js,并一直在尝试构建一个简单的天气应用程序。 GET 请求没有问题,因为控制台正在打印从 OpenWeatherMap API 接收到的 JSON 字符串,但是将 JSON 分配给局部变量然后访问其属性似乎存在问题。

getInitialState : function(){
        return (
            {weatherdata: null }
            );
    },

componentWillMount : function(){
    HttpService.get()
    .then(function(jsondata){
        console.log(jsondata);
        this.setState({weatherdata : jsondata});       
        }.bind(this));                                 
},

控制台给了我 2 个错误,反应开发工具拒绝加载: 未捕获的类型错误:无法读取 null 的属性 'main'

Uncaught (in promise) TypeError: Cannot read property '_currentElement' of null(...)

第一个指向我的行

React.createElement(今天,{ temp: this.state.weatherdata.main.temp,

这是渲染函数内部返回的sn-p

return(
    <div>
        <Today  temp={this.state.weatherdata.main.temp}
                windSpeed={this.state.weatherdata.wind.speed}
                windAngle={this.state.weatherdata.wind.deg}
                icon={this.state.weatherdata.weather[0].icon}
                iconID={this.state.weatherdata.weather[0].id}
                iconDesc={this.state.weatherdata.weather[0].description} />
     </div>
);

现在,如果我直接将所有数据粘贴到 weatherdata 对象中,它似乎可以正常工作。

已尝试 JSON.parse(),但这似乎无法解决问题。任何帮助将不胜感激。

【问题讨论】:

  • 嗯,你得到了初始状态 null,但是组件也被渲染为 null 状态,所以你在渲染 null 状态下访问这会导致错误。

标签: javascript json reactjs


【解决方案1】:

您正在以异步进程的形式请求某些内容,但希望在数据进入之前将其呈现。

尝试返回 null 直到数据进来

if(!this.state.weatherdata){
    return null;
}
return(
    <div>
        <Today  temp={this.state.weatherdata.main.temp}
                windSpeed={this.state.weatherdata.wind.speed}
                windAngle={this.state.weatherdata.wind.deg}
                icon={this.state.weatherdata.weather[0].icon}
                iconID={this.state.weatherdata.weather[0].id}
                iconDesc={this.state.weatherdata.weather[0].description} />
     </div>
);

话虽如此,我建议您使用像 lodash 这样具有 get 方法的库。通过消除 javascript 错误,它将极大地提高代码的稳定性。 get 方法接受一个变量并在其上搜索路径。

前:

var test = {john: ['billy', 'bob']};
console.log(_.get(test, 'john[1]'); // prints 'bob'
console.log(_.get(test, 'john[2]'); // prints 'undefined'
console.log(_.get(test, 'john[2].something.somethingElse'); // prints 'undefined'

如果你使用 lodash,这就是它的样子。

var weatherData = this.state.weatherdata;
return(
    <div>
        <Today  temp={_.get(weatherData, 'main.temp')}
                windSpeed={_.get(weatherData, 'wind.speed')}
                windAngle={_.get(weatherData, 'wind.deg')}
                icon={_.get(weatherData, 'weather[0].icon')}
                iconID={_.get(weatherData, 'weather[0].id')}
                iconDesc={_.get(weatherData, 'weather[0].description')} />
     </div>
);

【讨论】:

    猜你喜欢
    • 2016-03-25
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多