javascript - 如何在反应中有一组基于对象的路由?
问题描述
我正在学习反应。但是我对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”。有没有办法解决这个问题?提前致谢
解决方案
也许这个React-View-Router包可以帮助你。代替 react-router-dom,试试这个包,你可以按照 vue-router 的语法
推荐阅读
- javascript - 将引导折叠添加到具有行跨度的表格单元格
- java - 递归计算数组中的元素 - 大数组
- ruby - 在我的 Rails 应用程序上运行“heroku run rake db:migrate”时出现 YAML 语法错误
- kubernetes - Kubernetes 角色绑定:
:default 更改为 : -服务帐户 - postgresql - 没有时区比较的 POSTGRES 时间
- apache-spark - 在 Apache Spark 中跨集群读取数据
- javascript - 如何将 setTimeout() 与 CoffeeScript 重新同步?导轨 5
- arrays - PowerShell 搜索匹配超过 3 个 CSV... 执行缓慢
- javascript - 每秒更新 document.title
- javascript - JavaScript 正则表达式评估