2016-07-16 58 views
1

學習ReactJS。我創建了2個我想在組件中顯示的記錄,但不知道如何去做。我有:在組件中公開模型數據

toy_conroller.rb

class ToyController < ApplicationController 
    def index 
    @users = User.all 
    render component: 'usersList', props: { users: @users } 
    end 
end 

和看起來像一個組件:

userList.js.jsx

var usersList = React.createClass({ 
    propTypes: { 
    name: React.PropTypes.string, 
    age: React.PropTypes.number, 
    country: React.PropTypes.string, 
    }, 

    render: function() { 
     return (
      <div> 
      <h3>User List :D</h3> 
      <table style={{border: 1}}> 
       <thead> 
       <tr> 
        <th>Name</th> 
        <th>Age</th> 
        <th>Country</th> 
       </tr> 
       </thead> 
       <tbody> 
       <tr> 
        <td>{this.props.name}</td> 
        <td>{this.props.age}</td> 
        <td>{this.props.country}</td> 
       </tr> 
       </tbody> 
      </table> 
      </div> 
      ); 
    } 
}); 

如何獲取模型數據顯示上我的頁面?我在控制檯中看到了我的數據的JS對象,但不知道如何讓它們顯示在表中。

enter image description here

回答

1

this.props.users是對象的數組,你需要在所有的項目循環,並從他們每個人得到的數據

var UsersList = React.createClass({ 
 
    propTypes: { 
 
    users: React.PropTypes.array 
 
    }, 
 

 
    render: function() { 
 
    var users = this.props.users.map(function (user) { 
 
     return <tr key={ user.id }> 
 
     <td>{ user.name }</td> 
 
     <td>{ user.age }</td> 
 
     <td>{ user.country }</td> 
 
     </tr>; 
 
    }, this); 
 

 
    return <div> 
 
     <h3>User List :D</h3> 
 
     <table style={{border: 1}}> 
 
     <thead> 
 
      <tr> 
 
      <th>Name</th> 
 
      <th>Age</th> 
 
      <th>Country</th> 
 
      </tr> 
 
     </thead> 
 
     <tbody> 
 
      { users } 
 
     </tbody> 
 
     </table> 
 
    </div> 
 
    } 
 
}); 
 

 
var users = [ 
 
    { id: 1, name: 'name', age: 'age', country: 'country' }, 
 
    { id: 2, name: 'name-1', age: 'age-1', country: 'country-1' }, 
 
] 
 

 
ReactDOM.render(
 
    <UsersList users={ users } />, 
 
    document.getElementById('container') 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="container"></div>