首页 > 解决方案 > 如何在反应中有一组基于对象的路由?

问题描述

我正在学习反应。但是我对Vue很熟悉。在带有 Vue Router 的 Vue 中,我们可以拥有一组基于对象的路由,例如,

const routes = [
{
   name : "Login",
   path : "/login",
   component : ()=> import('views/Login.vue') //for lazy loading
   meta : {
    auth : false // this means no authentication needed for this particular route
    }
},
{
   name : "Dashboard",
   path : "/dashboard",
   component : ()=> import('views/Dashboard.vue') //for lazy loading
   meta : {
    auth : true // this means authentication needed for this particular route if the user is not authenticated, they will be redirected to login page
    },
}]

到目前为止,我尝试如下:

登录.jsx

const Login = () => {
  const onClick = () => {
    localStorage.setItem("token", "admin");
  };
  return <button onClick={onClick}>Login</button>;
};

export default Login;

仪表板.jsx

const Dashboard = () => {
  return <h1>Dashboard</h1>;
};

export default Dashboard;

应用程序.js

import React, { Fragment } from "react";
import { Redirect, Route, Switch } from "react-router-dom";
import Dashboard from "./Dashboard";
import Login from "./Login";

const App = () => {
  const routes = [
    {
      path: "/login",
      component: Login,
      auth: false,
    },
    {
      path: "/dashboard",
      component: Dashboard,
      auth: true,
    },
    {
      path: "/example",
      component: Example,
      auth: true,
    },
  ];
  return (
    <>
      <Switch>
        {routes.map((route, index) => {
          return (
            <Fragment key={index}>
              {route.auth ? (
                <>
                  <Route
                    exact
                    path={`${route.path}`}
                    component={route.component}
                  />
                 </>
              ) : (
                <>
                  <Route
                    exact
                    path={`${route.path}`}
                    component={route.component}
                  />
                </>
              )}
            </Fragment>
          );
        })}
      </Switch>
    </>
  );
};

export default App;

但在上述方法中,我总是被重定向到“/login”。有没有办法解决这个问题?提前致谢

标签: javascriptreactjs

解决方案


也许这个React-View-Router包可以帮助你。代替 react-router-dom,试试这个包,你可以按照 vue-router 的语法


推荐阅读