我需要用一些json数据初始化一个react组件,但不知道如何使用material-ui来做到这一点:
这就是我在 react 中要做的事情:
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以及通过 React 加载所有页面的路由,但我不知道如何将 json 传递到每个单独的页面。我想按以下方式使用它,将 comments.json 发送到我的 home 组件:
<Route name="root" path="/" handler={Main}>
<Route name="home" url="comments.json" handler={Home} />
<DefaultRoute handler={Home}/>
</Route>
有可能以某种方式实现这一目标吗?
最佳答案
最简单的方法是使用 jquery ajax 之类的方法在 componentWillMount
方法中加载 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 调用,并将数据作为 props 传递,但您会明白的。
关于javascript - 在单页应用程序上使用 json 数据的material-ui,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32712335/