繁体   English   中英

在多个react.js组件中渲染JSON数据

[英]Rendering json data in multiple react.js components

我想从json文件中获取一些值,并将它们呈现为多个组件。 此代码似乎无效。 请提出任何更改。 范围可能存在一些问题。

var App = React.createClass({

    getInitialState: function(){
      return { myData: [] }

    },
    showResults: function(response){
        this.setState(
          {myData: response}
          )
    },

    loadData: function(URL) {
      $.ajax({
        type: 'GET',
        dataType: 'jsonp',
        url: URL,
        success: function(response){
          this.showResults(response)
        }.bind(this)
      })
    },

    render: function(){
      this.loadData("fileLocation/sample.json");
      return(
        <div>
        {myData.key1}
        <Component1 value={myData.key2} />
        <Component2 value={myData.array[0].key3}/>
        </div>
      )
    }
  });

  var Component1 = React.createClass({
    render: function () {
      return(
        <div>{this.props.value}</div>
      )
    }
  });

  var Component2 = React.createClass({
    render: function () {
      return(
        <div>{this.props.value}</div>
      )
    }
  });
  ReactDOM.render(<App/>, document.getElementById('content'));

这是我要从中获取的sample.json文件。 即使这样也显示语法错误

{
  key1:"value1",
  key2:"value2",
  array: [
    {key3:"value3"},
    {key4:"value4"}
  ]
}

loadData [1]处正确调用showResults

var App = React.createClass({

    getInitialState: function(){
      return { myData: [] };
    },

    showResults: function(response){
        this.setState({
            myData: response
        });
    },

    loadData: function(URL) {
      var that = this;
      $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function(response){
          that.showResults(response);
        }
      })
    },

loadDatarender移至componentDidMount [2] ,并正确访问myData [3]

    componentDidMount: function() {
      this.loadData("fileLocation/sample.json");
    },

    render: function(){
      return(
        <div>
        {this.state.myData.key1}
        <Component1 value={this.state.myData.key2} />
        <Component2 value={this.state.myData.array[0].key3}/>
        </div>
      )
    }
});

保持Component1Component2不变:

var Component1 = React.createClass({
    render: function () {
      return(
        <div>{this.props.value}</div>
      )
    }
});

var Component2 = React.createClass({
    render: function () {
      return(
        <div>{this.props.value}</div>
      )
    }
});
ReactDOM.render(<App/>, document.getElementById('content'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM