2016-05-16 72 views
3

我想要做什么?React.js和Rails模型之间的通信

我不想在我的导轨上显示来自我的导轨模型的react.js组件的视图文件数据。

我有什么?

我已经安装了这些宝石

rails-admin 
react-rails 

我干了什么?

我创建了一个新的rails项目。 我安装了反应护栏宝石和Rails管理员宝石 创造了新的控制器,具有以下类型

轨摹支架帖子标题:绳体:文字

,我可以从轨添加管理员的职位都是好。

我的控制器看起来像:

class PostsController < ApplicationController 
    before_action :set_post, only: [:show, :edit, :update, :destroy] 

    # GET /posts 
    # GET /posts.json 
    def index 
    @posts = Post.all 
    end 

    # GET /posts/1 
    # GET /posts/1.json 
    def show 
    @post = Post.find(params[:id]) 
    end 

    # GET /posts/new 
    def new 
    @post = Post.new 
    end 

,这里是我的意见/职位/ index.html.erb文件

<%= react_component('PostList', {name: raw(render(template: 'posts/index', formats: :json)) }) %> 

这里是视图/职位/ index.json.jbuilder文件

json.array!(@posts) do |post| 
    json.extract! post, :id, :title, :body 
    json.url post_url(post, format: :json) 
end 

这里是视图/职位/ show.json.jbuilder文件

json.extract! @post, :id, :title, :body, :created_at, :updated_at 

这里是我的反应组件文件的资产/ Java脚本/组件/ post_list.js.jsx

var PostList = React.createClass({ 

    render: function() { 
    return (
     <div> 
     {JSON.parse(this.props.posts).map(function(post) { 
      return <Post key={post.id} {... post} />; 
     })} 
     </div> 
    ); 
    } 
}); 

,所以我不能明白的地方是我错了。我无法从json获取数据到index.html.erb。我怎样才能做到这一点?请帮助我是被卡住,我无法找到任何互联网上的理解

回答

0

我做了三个转变,使其工作:

  1. index.html.erb

    <%= react_component('PostList', 
          render(template: 'posts/index', formats: :json) 
         ) 
    %> 
    
  2. 意见/posts/index.json.jbuilder文件

    json.posts(@posts) do |post| 
        json.extract! post, :id, :title, :body 
        json.url post_url(post, format: :json) 
    end 
    

    按在documentation指示;即。 “确保你的JSON是一个字符串散列,而不是一个数组”。在PostList部件

  3. 删除JSON.parse函数渲染功能,这样:

    var PostList = React.createClass({ 
    
        render: function() { 
         return (
         <div> 
          {this.props.posts.map(function(post) { 
           return <Post key={post.id} {... post} />; 
          })} 
         </div> 
         ); 
        } 
    }); 
    
+0

您好,它不工作BU它正在工作。 –

0

此方法正在工作。

index.html.erb

<% @news.order("id DESC").each do |news| %> 
       <%= react_component('News', { :news => news }) %> 
       <% end %> 

news.js.jsx

var News = React.createClass({ 

displayName: 'News', 

    render: function() { 
    return (
      <div> 
      <h4>{this.props.news.title}</h4> 
      <p>{this.props.news.body}</p> 
      </div> 
    ); 
    } 
}); 

index.json.jbuilder

json.array!(@news) do |news| 
    json.extract! news, :id, :title, :body 
    json.url news_url(news, format: :json) 
end