我是React的新手,在为我要构建的简单用户管理表呈现用户列表方面一直很费劲。如果有人能够看到我在这方面出了错,那么如果您能让我知道,因为我已经花了很多时间在上面,阅读了我能找到的一切,但仍然没有成功,将不胜感激。>
我尝试了许多不同的变体,但这是我目前拥有的:
import React from 'react';
import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import PropTypes from 'prop-types';
class ManageUsers extends React.Component {
constructor(props) {
super(props);
this.state = {
users: []
};
}
renderUsers() {
return this.props.users.map((users) => {
return <ManageUsers key={users._id} user={users}/>;
});
};
render() {
return (
<div>
<li>{this.renderUsers()}</li>
</div>
);
}
};
ManageUsers.propTypes = {
users: PropTypes.array.isRequired
};
export default withTracker(() => {
Meteor.subscribe("users");
return {
users: Meteor.users.find({}).fetch()
}
})(ManageUsers);
我在浏览器控制台中收到一些与此不同的错误,包括:
未捕获的TypeError:无法读取未定义的属性“ map”
警告:道具类型失败:道具
users
被标记为ManageUsers
,但其值为undefined
。
答案 0 :(得分:0)
未捕获的TypeError:无法读取未定义的属性“ map”
要么测试在映射之前已定义users
,要么为其提供默认的prop值。
renderUsers = () => {
const { users } = this.props;
return users && users.map(user => <ManageUsers key={user._id} user={user}/>);
};
或
ManageUsers.defaultProps = {
users: [],
};
警告:道具类型失败:在ManageUsers中将道具用户标记为必需,但其值未定义。
这通常意味着,尽管它是必需的道具,但您可能并没有从父组件传递其定义的数据。
在这种情况下,似乎在安装React组件时,Meteor HOC没有提供users
数据。我对Meteor并不熟悉,但是也许您可以使订阅函数异步,并等待它使用users
道具的值来解析。
export default withTracker(async () => {
Meteor.subscribe("users");
return {
users: await Meteor.users.find({}).fetch()
}
})(ManageUsers);