gpt4 book ai didi

javascript - 将对象数组作为 React 组件的 Prop

转载 作者:行者123 更新时间:2023-11-29 21:09:32 25 4
gpt4 key购买 nike

我有一个名为 UsersTable 的父组件(它是某个其他组件的子集,并且有 usersroles 作为它的属性)。 getRoles() 函数使用 ajax 请求获取用户的所有 Angular 色。结果返回到 render() 并存储在 allroles 变量中。 allroles 是一个 Objects([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 时。您需要遍历它并为每个 Angular 色呈现一个元素

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

关于javascript - 将对象数组作为 React 组件的 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42385394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com