简体   繁体   中英

React JS with Rails - Accessing JSON data with URL

I'm learning how to use React JS with my Rails app. Disclaimer: This is the first time I am messing around with JS!

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).

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.

Here's my view,

<%= react_component "SongsContainer", { songsPath: songs_path } %>

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} />;
}
});

Any help would greatly be appreciated! I'm just looking at this 500 page not knowing what to do.

EDIT: Adding Server log

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!

  1. Remove Turbolinks from application.html.
  2. Replace the $.getJSON function with this,

    $.ajax({ url: this.props.songsPath, dataType: 'json', success: function(data) { this.setState({songs: data}); }.bind(this) });

Now, I really don't know much about JS, so I don't know why this works, but it just does! Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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