使用Rails进行React JS-使用URL访问JSON数据 [英] React JS with Rails - Accessing JSON data with URL
问题描述
我正在学习如何在我的Rails应用程序中使用React JS. 免责声明:这是我第一次搞砸JS!
I'm learning how to use React JS with my Rails app. Disclaimer: This is the first time I am messing around with JS!
我正在关注 Rails Conf上的Michael Chan 的演讲.一切正常,直到我点击CommentContainer部分,他从Rails路线中获取评论数据.除了在简单的Songs控制器(由脚手架生成,具有名称和艺术家作为属性)上,我正在尝试相同的事情.
I'm following a talk by Michael Chan at Rails Conf. Everything works beautifully until I hit the CommentsContainer part, where he fetches the comments data from a Rails route. I am trying to the same thing, except on a simple Songs controller (generated with a scaffold, having name and artist as the attribute).
我被卡在他用路径获取此数据的部分上,当我尝试运行代码时,出现500错误页面.我不知道如何调试我的React代码,因为浏览器控制台仅显示500错误.
I am getting stuck at the part where he fetches this data with the path, I end up with a 500 error page when I try to run the code. I don't know how to debug my React code, since the browser console is just showing a 500 error.
这是我的观点,
<%= react_component "SongsContainer", { songsPath: songs_path } %>
这是我的React代码,
And here's my React code,
var SongsContainer = React.createClass({
componentWillMount(){
this.fetchSongs();
setInterval(this.fetchSongs, 1000);
},
fetchSongs() {
$.getJSON(
this.props.songsPath,
(data) => this.setState({songs: data});
);
},
getInitialState() {
return { songs: [] };
},
render() {
return <Songs songs={this.state.songs} />;
}
});
任何帮助将不胜感激!我只是看这500页,不知道该怎么办.
Any help would greatly be appreciated! I'm just looking at this 500 page not knowing what to do.
添加服务器日志
Started GET "/" for ::1 at 2015-08-11 18:19:30 +0530
Processing by SongsController#index as HTML
Rendered songs/index.html.erb within layouts/application (0.6ms)
Completed 500 Internal Server Error in 373ms (ActiveRecord: 0.0ms)
ActionView::Template::Error (SyntaxError: unknown: Unexpected token (10:41)):
3: <head>
4: <title>Albums</title>
5: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
6: <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
7: <%= csrf_meta_tags %>
8: </head>
9: <body>
app/views/layouts/application.html.erb:6:in `_app_views_layouts_application_html_erb___3071413699732960348_70238909518380'
推荐答案
最后,经过很多努力,我找到了解决方法!
Finally after lots of struggle, I found a solution!
- 从application.html删除Turbolinks.
-
用此替换$ .getJSON函数,
- Remove Turbolinks from application.html.
Replace the $.getJSON function with this,
$.ajax({ 网址:this.props.songsPath, dataType:'json', 成功:功能(数据){ this.setState({songs:data}); } .bind(this) });
$.ajax({ url: this.props.songsPath, dataType: 'json', success: function(data) { this.setState({songs: data}); }.bind(this) });
现在,我真的对JS不太了解,所以不知道为什么会起作用,但是确实如此!干杯.
Now, I really don't know much about JS, so I don't know why this works, but it just does! Cheers.
这篇关于使用Rails进行React JS-使用URL访问JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!