如何在React js 0.13.3中访问嵌套对象

时间:2015-06-16 05:22:28

标签: javascript jquery html reactjs

以下添加的代码在React js 0.10.0中正常工作。我想在0.13.0版本中运行相同的代码。我的主要要求是访问嵌套对象作为默认对象,如“this.state.data.query.results.channel.item.condition.temp”。

<!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>

http://jsfiddle.net/xJvY5/

1 个答案:

答案 0 :(得分:2)

你应该 set initial state ,就像这样

getInitialState: function(){
    return {
        data: {
            query: {
                results: {
                    channel: {item: {condition: {temp: 0}}}     
                }
            }
        }
    };
},

Example - (v 0.10.0)

Example - (v 0.13.3) - 注意 - 在版本 0.13.3 中,您应该使用.render方法而不是.renderComponent

或者您可以使用data方法检查render,如果dataundefined - 则显示loading...。如果state已更新,则可以会看到你的data

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

render: function() {
  if (!this.state.data) {
       return <div>Loading...</div>;
  }
  ....
}

Example - (v 0.13.3)