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

标签 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/

最佳答案

您应该设置初始状态,就像这样

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

或者您可以在 render 方法中检查 data,如果 dataundefined - 显示 loading ...。,如果 state 已更新,您将看到您的数据

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

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

Example - (v 0.13.3)

关于javascript - 如何在 React js 0.13.3 中访问嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30859390/

相关文章:

php - 脚本运行时加载栏

html - CSS 和响应式设计

PHP POST 未填写

javascript - 将读卡器中的信用卡信息捕获到不可编辑的文本字段中

javascript - 关于Javascript能力的问题

javascript - 将 JS 对象传递到 HTML 字符串

javascript - 仅检查字母的正则表达式

javascript - 当页面是框架集的一部分并垂直调整大小时,在 IE7 中不会触发 body onresize 事件

javascript - 更改要素图层中多边形的顺序? (arcgis js 4.xx)

jquery UI 对话框默认第一个按钮样式