将一系列对象作为React组件的道具



i有一个名为 UsersTable的父组件(它是其他组件的智利,并以 users and roles为props)。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>
        );
    }
});

看起来问题是当您渲染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(){
        const roles = this.props.userRoles.map((role) => <div>{role.id || ''}</div>);
        return (
            <tr>
                <td>{this.props.userEmail}</td>
                <td>{roles}</td>
            </tr>
        );
    }
};

最新更新