2017-02-22 47 views
2

我有一個父組件,名爲UsersTable(它是一些其他組件的智慧,並具有usersroles作爲它的道具)。 getRoles()函數正在爲使用ajax請求的用戶獲取所有角色。結果返回到render()並存儲在allroles變量中。 allroles是對象數組([Object, Object, Object]),並將其作爲其道具發送給子組件UserRow。但我得到這個錯誤:將對象數組作爲React組件的道具

invariant.js:44 Uncaught Error: Objects are not valid as a React child 
(found: object with keys {description, id, links, name}). If you meant to render a 
collection of children, use an array instead or wrap the object using 
createFragment(object) from the React add-ons. Check the render method of 
`UserRow`. 

有人可以幫我解決它嗎?下面是父組件代碼:

export const UsersTable = React.createClass({ 
    getRoles(){ 
     var oneRole = ""; 
     this.props.users.forEach(function(user){ 
      server.getUserRoles(user.id,   
       (results) => { 
        this.oneRole =results['hits']['hits'] 
        notifications.success("Get was successful "); 
       }, 
       () => { 
        notifications.danger("get failed "); 
       }); 
      }.bind(this)); 
     return this.oneRole; 
    }, 

    render() { 
     var rows = []; 
     var allroles = this.getRoles() 
     this.props.users.map(function(user) { 
      rows.push(<UserRow userID={user.id} 
           userEmail={user.email} 
           userRoles={allroles} 
           roles={this.props.roles} />); 
      }.bind(this)); 
     return (
      <table className="table"> 
       <thead> 
        <tr> 
         <th>Email Address</th> 
         <th>Role</th> 
         <th>Edit</th> 
        </tr> 
       </thead> 
       <tbody>{rows}</tbody> 
      </table> 
     ); 
    }  
}); 

這裏是子組件代碼:

export const UserRow = React.createClass({ 
    render(){ 
     return (
      <tr> 
       <td>{this.props.userEmail}</td> 
       <td>{this.props.userRoles}</td> 
      </tr> 
     ); 
    } 
}); 
+0

這是因爲是的UserRole的對象和要打印它作爲一個字符串。您需要通過循環將它存儲在變量中,而不是隻能打印該變量。 – SPViradiya

回答

1

貌似問題是,當你渲染的UserRole。你需要循環,並呈現一個元素爲每個角色

export class UserRow extends React.Component { 
    render(){ 
     return (
      <tr> 
       <td>{this.props.userEmail}</td> 
       <td>{this.props.userRoles}</td> 
--------------------^---------------------^ 
      </tr> 
     ); 
    } 
}; 

試試這個

export class UserRow extends React.Component { 
    render(){ 
     constroles = this.props.userRoles.map((role) => <div>{role.id || ''}</div>); 
     return (
      <tr> 
       <td>{this.props.userEmail}</td> 
       <td>{roles}</td> 
      </tr> 
     ); 
    } 
}; 
+0

謝謝! 'allroles'中的每個對象都是一個帶有這些鍵的字典:description,id,links,name。所以只需要編輯你的答案來獲得正確的價值。而不是'{role}',應該是'{role ['id']}' – Birish

+0

@sarah真棒!很高興幫助我更新了我的答案:) –

相關問題