【问题标题】:How to access nested object in React js 0.13.3如何在 React js 0.13.3 中访问嵌套对象
【发布时间】:2015-08-31 18:54:57
【问题描述】:

下面添加的代码在 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/

【问题讨论】:

    标签: javascript jquery html reactjs


    【解决方案1】:

    你应该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

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

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

    Example - (v 0.13.3)

    【讨论】:

    • 我遇到了一个类似的问题,我无法通过常规点符号访问嵌套对象。为什么设置状态时需要指定对象的完整嵌套结构?
    猜你喜欢
    • 2023-03-21
    • 2021-09-01
    • 1970-01-01
    • 2021-08-17
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 2018-03-14
    相关资源
    最近更新 更多