【发布时间】:2021-10-16 02:01:55
【问题描述】:
我是 Nodejs 和 React 的新手,在渲染之前尝试运行函数时遇到问题。我设置了一个页面,允许管理员查看在网站上注册的所有用户,如果有用户,它就可以正常工作。但是,当用户尝试访问此 ViewUsers 页面时,授权中间件会发送一个响应,说明不允许他们查看该页面。然后将 users 设置为空,这会在 user.map() 函数在渲染中运行时出现问题。 notfound 页面应该在渲染运行之前在 checkAuth() 函数中运行。我收到此错误
TypeError: users.map is not a function
这是我查看用户页面的代码。
import React, { Component } from "react";
import AdminServices from "../Services/AdminServices";
import "././ViewUsers.css"
export default class ViewUsers extends Component {
constructor(props) {
super(props);
this.retrieveUsers = this.retrieveUsers.bind(this);
this.checkAuth = this.checkAuth.bind(this);
this.state = {
users: []
}
}
componentDidMount() {
this.retrieveUsers();
}
retrieveUsers() {
AdminServices.getAllUsers()
.then(response => {
this.setState({
users: response.data
});
console.log(response.data);
console.log('DATA RECEIVED')
this.checkAuth();
})
.catch(e => {
console.log('ERROR')
console.log(e);
});
}
checkAuth() {
if (this.state.users.length === 0) {
window.location = '/notfound'
}
}
render () {
const { users } = this.state;
return (
<div className="viewusers">
<h1>All users</h1>
<div className="viewusers-list">
{users.map((user) => {
return (
<React.Fragment>
<p> <b>Name</b> : {user.username} </p>
<p> <b>Email</b> : {user.email} </p>
<p> <b>Website role</b> : {user.websiteRole} </p>
<hr />
</React.Fragment>
)
})}
</div>
</div>
)
}
}
【问题讨论】:
-
你确定
users是一个数组吗? -
你的路由在节点中是什么样子的?通常,auth 中间件将成为路由的一部分并传递 next() 函数。这样您就可以进行身份验证,如果找到,则转到路线中的下一个功能。