我正在学习react,我试着在app.tsx中做路由,比如:
import { Route, Routes, Navigate } from "react-router-dom";
import ProtectedRoute from "./components/protectedRoute";
import { HomePage, AboutPage, LoginPage, TestPage, MyApp1 } from "./pages/_pages";
import Layout from "./components/layout";
function App() {
return (
<>
<Routes>
<Route path="/" element={<ProtectedRoute outlet={<Layout />} />}>
<Route index element={<ProtectedRoute outlet={<HomePage />} />} />
<Route path="about" element={<ProtectedRoute outlet={<AboutPage />} />} />
<Route path="myapp1" element={<ProtectedRoute outlet={<MyApp1 />} />}>
<Route path=":command" element={<ProtectedRoute outlet={<MyApp1 />} />}></Route>
<Route path=":command/:id" element={<ProtectedRoute outlet={<MyApp1 />} />}></Route>
</Route>
</Route>
<Route path="login" element={<LoginPage />} />
<Route path="*" element={<Navigate to="/login" />} />
</Routes>
</>
);
}
export default App;
我可以创建这样的类型:
export type AllowedCommands = "new" | "edit";
export type URLParams = {
command: AllowedCommands;
id?: string;
};
myapp 1页面:
import { useParams } from "react-router-dom";
import { URLParams } from "../Models/interfaces/AppPageParams";
const MyApp1 = () => {
const pagePara = useParams<URLParams>();
return (
<AppLayout>
<p>Command 2 : {pagePara.command}</p>
{pagePara.id && <p>ID: {pagePara.id}</p>}
</AppLayout>
);
};
export default MyApp1;
对于http://localhost:3000/myapp 1/* 任何是好的,但我想使命令只允许新的或编辑的规则,如果编辑,它必须提供ID,所以我期望
- http://localhost:3000/myapp1/=>将http://localhost:3000/myapp1
- http://localhost:3000/myapp1/new/=>将http://localhost:3000/myapp1/new(which pagePara.command = new)
- http://localhost:3000/myapp 1/edit/1 =>将http://localhost:3000/myapp 1/edit/1(其中pagePara.command = edit且id =1)
- http://localhost:3000/myapp 1/edit =>将重定向http://localhost:3000/myapp 1
- http://localhost:3000/myapp 1/wrong =>将重定向http://localhost:3000/myapp 1
我能知道怎么做吗?
1条答案
按热度按时间gudnpqoy1#
React-Router路由要么匹配路径,要么不匹配路径。像
"/myapp1/wrong"
这样的URL路径将被"/myapp1/:command"
匹配,并且MyApp1
组件将被呈现。MyApp1
组件需要从路由参数中读取command
值,并实现自己的验证。这里有一个简单的验证。
由于
MyApp1
没有呈现Outlet
组件,因此不需要呈现任何嵌套路由。使用:command
和:id
参数渲染单个路由,这些参数列为可选参数(* 自v6.5.0* 起可用)。Demo