【问题标题】:How to bind data from getJSON to ReactJS state如何将数据从 getJSON 绑定到 ReactJS 状态
【发布时间】:2015-09-28 07:10:13
【问题描述】:

我一直在尝试从 JSON 文件中获取数据并使用 ReactJS 将其绑定到我的页面

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Demo Fetch</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
    <script src="js/jquery-2.1.4.min.js"></script>
</head>
<body>
    <div id="content"></div>
    <script type="text/jsx">
        var DataBlock = React.createClass({
            getInitialState:function(){
                return {};
            },
            loadData:function() {
                var a=this;
                $.getJSON(this.props.url, function (obj) {
                    a.setState({data: obj})
                });
            },
            render: function() {
                return (
                        <div className="dataBlock" data={this.state.data}>
                            <h1>Sample data block</h1>
                                {this.loadData()}
                                <h3>{data.runtime}</h3>
                        </div>
                );
            }
        });
        React.render(
                <DataBlock url="small_data.json"/>,
                document.getElementById('content')
        );
    </script>
</body>
</html>

但是当我尝试显示页面时没有显示任何内容。我的代码有什么问题?它的漏洞在哪里?为什么我不能将来自 getJSON 的数据绑定到我的 React 组件的状态?

这是我的small_data.json 文件:

{
  "movies": [
    {
      "abridged_cast": [
        {
          "characters": [
            "Dominic Toretto"
          ],
          "id": "162652472",
          "name": "Vin Diesel"
        },
        {
          "characters": [
            "Brian O'Conner"
          ],
          "id": "162654234",
          "name": "Paul Walker"
        }
      ],
      "runtime": 140,
      "synopsis": "Continuing the global exploits in the unstoppable franchise built on speed, Vin Diesel, Paul Walker and Dwayne Johnson lead the returning cast of Fast & Furious 7. James Wan directs this chapter of the hugely successful series that also welcomes back favorites Michelle Rodriguez, Jordana Brewster, Tyrese Gibson, Chris \"Ludacris\" Bridges, Elsa Pataky and Lucas Black. They are joined by international action stars new to the franchise including Jason Statham, Djimon Hounsou, Tony Jaa, Ronda Rousey and Kurt Russell.",
      "title": "Furious 7",
      "year": 2015
    }
  ],
  "runtime": 140
}

【问题讨论】:

    标签: json ajax reactjs bind react-jsx


    【解决方案1】:

    你需要使用componentDidMount: function() { 加载数据

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    const data = {
      "movies": [
        {
          "abridged_cast": [
            {
              "characters": [
                "Dominic Toretto"
              ],
              "id": "162652472",
              "name": "Vin Diesel"
            },
            {
              "characters": [
                "Brian O'Conner"
              ],
              "id": "162654234",
              "name": "Paul Walker"
            }
          ],
          "runtime": 140,
          "synopsis": "Continuing the global exploits in the unstoppable franchise built on speed, Vin Diesel, Paul Walker and Dwayne Johnson lead the returning cast of Fast & Furious 7. James Wan directs this chapter of the hugely successful series that also welcomes back favorites Michelle Rodriguez, Jordana Brewster, Tyrese Gibson, Chris \"Ludacris\" Bridges, Elsa Pataky and Lucas Black. They are joined by international action stars new to the franchise including Jason Statham, Djimon Hounsou, Tony Jaa, Ronda Rousey and Kurt Russell.",
          "title": "Furious 7",
          "year": 2015
        }
      ],
      "runtime": 140
    }
    
    const DataBlock = React.createClass({
        getInitialState: () => {
          return {
            data: null
          };
        },
    
        componentDidMount: () => {
                    this.setState({
                        data: this.props.url
                    });   
       },             
        render() {
            return <div>
            <h3>runtime: {data.runtime}</h3>
            <h4>the data:</h4> 
            {this.state.data}
            </div>;
        }
    });
    
    
    ReactDOM.render(<DataBlock url={data}/>, document.getElementById('.container'));
    

    https://jsfiddle.net/63nL7yfj/

    【讨论】:

    • 谢谢。完成了,我想问一个小问题:当我写console.log(this.state.movies);时控制台显示movies的数组但是当我写console.log(this.state.movies[0]);时它显示错误,我无法访问movies数组中的对象。我该怎么做?
    • 你不能 console.log 声明它不能那样工作。这就是你的意思吗? jsfiddle.net/f1x9ur21
    • 我要获取movies的数据。我可以通过{data.runtime} 访问runtime。但是当我尝试通过{data.movies[0].title} 访问movies 中第一个对象的title 时,什么都没有显示
    猜你喜欢
    • 2019-07-13
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多