作为React组件的props,拥有一个对象数组

3

我有一个名为UsersTable的父组件(它是某个其他组件的子组件,并具有usersroles作为其props)。 getRoles()函数正在使用ajax请求获取用户的所有角色。结果返回到render()并存储在allroles变量中。 allroles是一个对象数组([Object, Object, Object]),并作为其props发送到子组件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是一个对象,而你试图将其作为字符串打印出来。你需要通过循环将其存储在一个变量中,然后你就可以直接打印该变量了。 - SPViradiya
1个回答

2

看起来问题出在你渲染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>
        );
    }
};

谢谢!allroles 中的每个对象都是一个字典,包含以下键:description、id、links 和 name。因此,只需要编辑您的答案即可获得正确的值。将 {role} 替换为 {role['id']} 即可。 - Birish
@sarah 太棒了!很高兴能帮到你,我也更新了我的答案 :) - John Ruddell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接