反应导航更改位置但不渲染组件

时间:2020-10-08 10:04:09

标签: reactjs

如果我尝试登录我的应用程序,则发布该帖子,并更新authReducer:

.NET Core 5.0

地址从/ login更改为/ user,但是/ user组件未呈现,并且保留在登录页面上。 登录功能:

isAuthenticated: true
loading: false
user: {user: {…}, iat: 1602150047, exp: 1602160047

并在“登录”表单上调用它:

export const loginUser = (
  email: string,
  password: string,
  from: string
) => async (dispatch: Dispatch) => {
  try {
    const result = await axios.post("http://localhost:3000/api/users/login", {
      email,
      password,
    });
    console.log(result);
    const { access_token } = result.data;
    localStorage.setItem("JWT_TOKEN", access_token);
    //set token to auth header
    setAuthToken(access_token);

    //decode token to get user data
    const decoded = jwt_decode(access_token);

    //set current
    dispatch(setCurrentUser(decoded));
    history.push(from);
  } catch (error) {
    throw new error();
  }
};

在我的应用上:

function handleSubmit(e) {
    e.preventDefault();

    setSubmitted(true);
    if (email && password) {
      const { from } = location.state || { from: { pathname: "/user" } };
      dispatch(loginUser(email, password, from));
    }
  }

路线:

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import setAuthToken from "./config/SetAuthToken";
import jwt_decode from "jwt-decode";
import { logoutUser, setCurrentUser } from "./app/services/auth.service";
import { useDispatch } from "react-redux";
import routesConfig from "./config/Routes.Config";
import PrivateRoute from "./config/PrivateRoute";

function App() {
  const dispatch = useDispatch();
  if (localStorage.getItem("JWT_TOKEN")) {
    // Set auth token header auth
    const access_token = localStorage.getItem("JWT_TOKEN");
    setAuthToken(access_token);
    // Decode token and get user info and exp
    const decoded: any = jwt_decode(access_token);
    // Set user and isAuthenticated
    dispatch(setCurrentUser(decoded));
    // Check for expired token
    const currentTime = Date.now() / 1000; // to get in milliseconds
    if (decoded.exp < currentTime) {
      // Logout user
      dispatch(logoutUser());
      // Redirect to login
      window.location.href = "./searchVehicles";
    }
  }

  return (
    <div>
      <Router>
        <Switch>
          {routesConfig.routes.map(({ component, roles, url }) =>
            roles.length ? (
              <PrivateRoute
                exact
                path={url}
                component={component}
                roles={roles}
              />
            ) : (
              <Route exact path={url} component={component} />
            )
          )}
        </Switch>
      </Router>
    </div>
  );
}

export default App;

PrivateRoute

import Admin from "../components/Admin/Admin";
import LandingPage from "../components/Landing/LandingPage";
import Login from "../components/Login/Login";
import RecipeList from "../components/Recipes/RecipeList";
import Register from "../components/Register/Register";
import UserPage from "../components/Users.js/UserPage";

export default {
  routes: [
    {
      component: Login,
      url: "/login",
      roles: [],
    },
    {
      component: Register,
      url: "/register",
      roles: [],
    },
    {
      component: LandingPage,
      url: "/",
      roles: [],
    },
    {
      component: UserPage,
      url: "/user",
      roles: ["user"],
    },
    {
      component: RecipeList,
      url: "/recipelist",
      roles: ["recipe"],
    },
    {
      component: Admin,
      url: "/admin",
      roles: ["recipe"],
    },
  ],
};

自定义历史记录

import React from "react";
import { Route, Redirect, RouteProps } from "react-router-dom";
import { useSelector } from "react-redux";

interface IPrivateRouteProps extends Omit<RouteProps, "component"> {
  component: React.ElementType;
  roles: string[];
}

const PrivateRoute = ({
  component: Component,
  roles = [],
  ...rest
}: IPrivateRouteProps) => {
  const auth = useSelector((state: any) => state.authReducer);
  const userRoles: any = auth.user.role ?? [];
  // check the route's roles to see if any match a role the user has
  const hasRole = roles.some((role) => userRoles.includes(role));
  if (!Component) return null;

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

export default PrivateRoute;

有人知道我在做什么错吗?

0 个答案:

没有答案