2014-05-03 155 views
2

我正在浏览响应入门教程,并遇到了一个我正在做的实验中的问题。我能够记录一个对象,但在控制台中,我得到以下错误:ReactJS中的嵌套对象

遗漏的类型错误:无法未定义

读取属性“结果”我可以登录的对象,所以我知道我的API调用成功,但由于某种原因,我的反应状态似乎没有得到更新。我认为我的渲染函数在我的数据对象从API更新之前发生,但不知道如何修复它。

http://jsfiddle.net/xJvY5/

<!doctype html> 
<html> 
<head> 
    <title>Weather Widget</title> 
    <link rel="stylesheet" href="weather.css" /> 
    <script src="http://fb.me/react-0.10.0.js"></script> 
    <script src="http://fb.me/JSXTransformer-0.10.0.js"></script> 
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> 
</head> 
<body> 
<script type="text/jsx"> 
    /*** @jsx React.DOM */ 
    var weatherWidget = React.createClass({ 
     loadData: function(){ 
      $.ajax({ 
       url: 'http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%2222102%22&format=json', 
       dataType : "jsonp", 
       cache: false, 
       success: function(data) { 
        console.log(data) 
        this.setState({data: data}); 
       }.bind(this) 
      }); 
     }, 
     getInitialState: function(){ 
      return {data: []}; 
     }, 
     componentWillMount: function(){ 
      this.loadData(); 
     }, 
     render: function(){ 
      return(
       <div className="ww-container"> 
        <div className="ww-current-condition"> 
         <div className="ww-current-temperture">{this.state.data.query.results.channel.item.condition.temp}&deg;</div> 
        </div> 
       </div> 
      ) 
     } 
    }); 

    React.renderComponent(<weatherWidget />, document.body); 
</script> 
</body> 

</html> 

回答

6

问题是,反应是试图同时它尚未获取访问API调用的结果。访问嵌套对象时应该添加空检查(这是一个JavaScript问题,而不是特定于React的东西)。

其次,尽管数据不可用,但您的组件仍会尝试渲染某些内容。 React会在您将组件注入页面时呈现您的组件,因此请考虑在API结果尚未保存到状态时显示“加载”指示符。

这是你拨弄适当null检查& “负载指标” 的一个分支:

http://jsfiddle.net/jxg/9WZA5/

render: function(){ 
    var degrees = this.state.item ? this.state.item.condition.temp : 'loading...'; 
    return(
    <div className="ww-container"> 
     <div className="ww-current-condition"> 
     <div className="ww-current-temperture">{degrees}&deg;</div> 
     </div> 
    </div> 
); 
+0

这是有帮助的。非常感谢! – skooliano