仅在用户具有管理员角色(React,Express,NodeJS,MongoDB)时访问页面

问题描述 投票:0回答:2

我想允许访问一个页面,“用户”,该页面显示在网站上注册的所有用户,仅当该用户为管理员时,

这是页面的组成部分:

<Route path="/users" exact component={Users} />

我尝试了类似的方法,但是没有用:

Router.js

<AdminRoute path="/users" exact component={Users} />



AdminRoute/index.js

import React, { useEffect, useState } from "react";
import { Route, Redirect } from "react-router-dom";
import axios from "axios";
import M from "materialize-css";
import { connect } from "react-redux";

function AdminRoute({ component: Component, auth, ...rest }) {
  const [user, setUser] = useState(false);

  async function loadUser() {
    try {
      const dataUser = await axios.get(
        `http://localhost:5000/api/users/my-account/${auth.user.id}`
      );
      setUser(dataUser.data);
      console.log("user ", user); <-- returns well an object with isAdmin = 
      true
      M.AutoInit();
    } catch (error) {
      console.log(error);
    }
  }

  useEffect(() => {
    if (auth.isAuthenticated) {
      loadUser();
    }
  }, []);

  return (
    <Route
      {...rest}
      render={props =>
        auth.isAuthenticated && user.isAdmin ? (
          <Component {...props} />
        ) : (
          <Redirect to="/" />
        )
      }
    />
  );
}

const mapStateToProps = state => ({
  auth: state.auth
});
export default connect(mapStateToProps)(AdminRoute);

主要问题是,如果有管理员帐户,我将被重定向

node.js reactjs express
2个回答
0
投票

尝试像下面一样在mapStateToProps中返回auth

const mapStateToProps = state => {
return {
  auth: state.auth
}
};

希望这会有所帮助。如果您有任何问题,请告诉我。


0
投票

这是某种嵌套路线吗?我确定您可以将其设置为在您的路由页面上使用,但是我一直都在使用诚实和声明来完成页面本身中的工作。

{isAdmin && <div />}

在调用组件上的render()之前,您总是可以询问if (!isAdmin) props.history.push('/');

© www.soinside.com 2019 - 2024. All rights reserved.