javascript - ReactJs 记录收到的道具数组显示空数组
问题描述
我的代码通过这些组件显示用户列表:
用户.js
class Users extends Component {
state = {
usersInformation: []
};
componentDidMount() {
getUsersDataFromDB()
.then(result => {
this.setState({
usersInformation: result.data
});
})
.catch(error => console.error("(1) Outside error:", error));
}
render() {
console.log("this.state.usersInformation");
console.log(this.state.usersInformation);
return (
<div className="animated fadeIn">
<Fragment>
<UsersList usersInformation={this.state.usersInformation} />
</Fragment>
</div>
);
}
}
用户列表.js
class UsersList extends Component {
constructor(props) {
super(props);
this.state = {
pagesCount:2,
currentPage: 0,
pageSize: 5
};
}
componentDidMount() {
console.log('componentDidMount: this.props.usersInformation')
console.log(this.props.usersInformation)
}
componentWillReceiveProps() {
console.log('componentWillReceiveProps: this.props.usersInformation')
console.log(this.props.usersInformation)
}
render() {
return (
<React.Fragment>
<Row>
<Card>
<CardHeader>
<i className="fa fa-align-justify"></i> Admins{" "}
<small className="text-muted">
La liste complète des admins{" "}
</small>
</CardHeader>
<CardBody>
<Table responsive hover>
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Nom</th>
<th scope="col">Email</th>
<th scope="col">Role</th>
{/* TODO: Derniere == Dernière problem with UTF */}
<th scope="col">Derniere connexion</th>
</tr>
</thead>
<tbody>
{this.props.usersInformation
.slice(
this.state.currentPage * this.state.pageSize,
(this.state.currentPage + 1) * this.state.pageSize
)
.map(userInformation => {
return (
<tr key={userInformation.id.toString()}>
<td>{userInformation.id}</td>
<td>{userInformation.nom}</td>
<td>{userInformation.email}</td>
<td>{userInformation.role}</td>
<td>{userInformation.derniereCnx}</td>
</tr>
);
})}
</tbody>
</Table>
</CardBody>
</Card>
</Row>
</React.Fragment>
);
}
}
这给出了以下结果:
在 User.js 中,我从数据库中检索 usersInformation 并将其作为道具传递给 UsersList。
问题是,当我在UserList.js中记录usersInformation时,在两个方法componentWillReceiveProps和componentDidMount中,它们都显示一个空数组,尽管用户信息可以完美显示:
Users.js:37 this.state.usersInformation
Users.js:38 []
UsersList.js:20 componentDidMount:this.props.usersInformation
UsersList.js:21 []
Users.js:37 this.state.usersInformation
Users.js:38 (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
UsersList.js:25 componentWillReceiveProps: this.props.usersInformation
UsersList.js:26 []
所以我想这是React组件UsersList的生命周期问题?
为了能够记录 usersInformation 数组,我应该使用哪种生命周期方法?
解决方案
推荐阅读
- c - 为什么可以在 scanf 的转换说明符中嵌入空字符?
- python - 除法运算符重载参数具有相同的值
- image-processing - 在网络摄像头上部署 pytorch 模型
- mysql - 求和到某个特定值后,如何在 MySQL 中从上到下跳过和检索所有行?
- package - 如何确定自制程序包是否针对苹果 M1 进行了优化
- javascript - 我想在 postgress 中插入一个数组类型的数组,但我不知道如何从节点执行它
- ansible - 证书授权。: 指定的凭据被服务器拒绝
- php - 在 WooCommerce 中选择“本地取货”时,不要对某些产品类别给予折扣
- oracle - 年份的日期差异
- jquery - 如何合并调整大小和滚动功能 - Jquery