2016-09-22 60 views
0

我是ReactJs的新手。我創建了一個用戶填充網格的小應用程序,當點擊與用戶關聯的按鈕時,應用程序將重定向到包含有關用戶信息的頁面(作爲道具傳遞)。我已經使用路由器來處理這個頁面請求:通過道路傳遞道具到頁面的問題

<Router> 
<Route path="/" header="Main Page" component={() => (<MainPage content={users}/>)}> 
</Route> 
<Route path="/UserName" header="User Page" component={UserPage}/> 
</Router> 

網格頁面,它工作正常,並獲取數據從父組件道具如下:

var React = require('react'); 
var ReactRouter = require('react-router'); 
var Link = ReactRouter.Link; 
var Prompt = require('../components/Prompt'); 

var UsersList = React.createClass({ 
    accessUserInfo: function (user) { 
    this.context.router.push('/UserName', query={user}); 
    }, 
    render: function(){ 
    return(
     <form> 
     <table> 
     <tbody> 
     <tr> 
      <th>Name</th> 
      <th>Surname</th> 
      <th>Day of Birth</th> 
      <th>Username</th> 
      <th>Role</th> 
      <th></th> 
     </tr> 
     {this.props.content.map(function(user, i) { 
      return (
      <tr key={i}> 
       <td>{user.name}</td> 
       <td>{user.surname}</td> 
       <td>{user.birthday}</td> 
       <td>{user.userName}</td> 
       <td>{user.userRole}</td> 
       <td> 
       <Link> 
        <button type="submit" onSubmit={this.accessUserInfo(user)}>Open</button> 
       </Link> 
       </td> 
      </tr> 
     ); 
     }.bind(this))} 
     </tbody> 
     </table> 
    </form> 
    ) 
} 

})

UsersList.contextTypes = { 
    router: React.PropTypes.object.isRequired 
} 

module.exports = UsersList; 

用戶頁面,很基本的,如下:

var React = require('react'); 

var UserPage = React.createClass({ 
    render: function() { 
    return(
    <table> 
    <tbody> 
    <h1> 
    Information for User {this.props.user.userName} 
    </h1> 
    <tr> 
     <td>Name: </td> 
     <td>{this.props.user.name}</td> 
     </tr> 
    <tr> 
     <td>Surname: </td> 
     <td>{this.props.user.surname}</td> 
    </tr> 
    <tr> 
     <td>Role: </td> 
     <td>{this.props.user.userRole}</td> 
    </tr> 
    </tbody> 
    </table> 
) 

}});

module.exports = UserPage; 

我有2個問題:

  • 的accessUserInfo()方法被調用用於陣列中的每個項目,而不管國稅發被點擊按鈕
  • 用戶頁面加載,但用戶道具沒有傳遞到組件,因爲我得到

無法讀取的不確定

01房產「用戶名」

任何幫助將非常感激,謝謝提前

+0

後嘗試這樣'的onSubmit = {()=> this.accessUserInfo(用戶)}' – elmeister

回答

2

爲了避免accessUserInfo()被稱爲對於每個項目,使用箭頭功能sintax:onSubmit={()=>this.accessUserInfo(user)}

但是,我認爲你不需要這種方法並且您需要稍微更改設計,因爲您無法將對象作爲屬性發送。例如,如果您要發送用戶的ID(爲了從商店或API獲取UserPage組件的用戶),可以直接使用鏈接設置屬性。這是解釋here。只要使用,例如

<Link to={"UserName/"+userId}></Link>

改變路由至類似

<Route path="/UserName/:userId" header="User Page" component={UserPage}/>