将一个Object数组作为React组件的道具

时间:2017-02-22 07:40:10

标签: javascript ajax reactjs

我有一个名为UsersTable的父组件(它是一些其他组件的智慧组件,并且usersroles作为其道具)。 getRoles()函数使用ajax请求获取用户的所有角色。结果返回render()并存储在allroles变量中。 allroles是一个对象数组([Object, Object, Object]),并作为其道具发送到子组件UserRow。但是我收到了这个错误:

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

1 个答案:

答案 0 :(得分:1)

看起来像是渲染userRoles时的问题。你需要遍历它并为每个角色渲染一个元素

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