【问题标题】:material-ui using json data on single page applicationmaterial-ui 在单页应用程序上使用 json 数据
【发布时间】:2015-12-19 03:55:16
【问题描述】:

我需要用一些json数据初始化一个react组件,但是不知道怎么用material-ui做这个:

这就是我的反应方式:

var CommentList = React.createClass({
  render: function() {
    var commentNodes = this.props.data.map(function (comment) {
      return (
        <Comment author={comment.author}>
          {comment.text}
        </Comment>
      );
    });
    return (
      <div className="commentList">
        {commentNodes}
      </div>
    );
  }
});

React.render(
  <CommentBox url="comments.json" />,
  document.getElementById('content')
);

但我现在正在使用带有material-ui 的单页应用程序和路由,所有页面都通过反应加载,但我不知道如何将 json 传递给每个单独的页面。我想通过以下方式使用它,将 cmets.json 发送到我的主组件:

<Route name="root" path="/" handler={Main}>
   <Route name="home" url="comments.json" handler={Home} />
   <DefaultRoute handler={Home}/>
</Route>

有没有可能以某种方式实现这一目标?

【问题讨论】:

  • 您是否正在异步加载json (ajax)?
  • 我不太清楚你的意思,但数据应该异步加载,我认为这会发生在 Route 组件的后台,然后它将作为道具传递给 Home 组件?还是我需要以某种方式在我的 Home 组件中加载数据?

标签: javascript reactjs react-router material-ui


【解决方案1】:

最简单的方法是在componentWillMount 方法中使用jquery ajax 之类的方法加载json

var CommentList = React.createClass({
  componentWillMount: function () {
    $.get('comments.json').done(function (json) {
      this.setState({comments: json});
    }.bind(this));
  },
  render: function() {
    var commentNodes = this.state.comments.map(function (comment) {
      return (
        <Comment author={comment.author}>
          {comment.text}
        </Comment>
      );
    });
    return (
      <div className="commentList">
        {commentNodes}
      </div>
    );
  }
});

您显然可以在 Main 组件中进行 ajax 调用并将数据作为道具传递,但您会明白的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 2021-02-14
    相关资源
    最近更新 更多