在 React.js 中定义完全类型安全的路由最简单的方式,你只需要使用 3 个 api。Vue3 版本在这里 (https://github.com/qinjialei24/vue-typesafe-router).
npm i react-typesafe-router
#or
pnpm i react-typesafe-router
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import {
createTypesafeRoute,
useTypesafeNavigate,
useTypesafeQuery,
} from "react-typesafe-router";
const barTypesafeRoute = createTypesafeRoute<{ name: string; age?: number }>({
path: "/bar",
element: <Bar />,
});
const fooTypesafeRoute = createTypesafeRoute<{ name: string; age?: number }>({
path: "/foo",
element: <Foo />,
});
const router = createBrowserRouter([
{
path: "/",
element: <Foo />,
},
fooTypesafeRoute,
barTypesafeRoute,
]);
import { useTypesafeNavigate } from "react-typesafe-router";
function Foo() {
const navigateToBar = useTypesafeNavigate(barTypesafeRoute);
return (
<div>
<h3>Hello Foo!</h3>
<button onClick={() => navigateToBar({ name: "jack" })}>Go to Bar</button>
</div>
);
}
现在,您可以传递类型安全的路由查询数据!
import { useTypesafeNavigate, useTypesafeQuery } from "react-typesafe-router";
function Bar() {
const barQuery = useTypesafeQuery(barTypesafeRoute);
const navigateToFoo = useTypesafeNavigate(fooTypesafeRoute);
return (
<div>
<h3>Hello Bar!</h3>
<h3>name: {barQuery.name}</h3>
<h3>age: {barQuery.age}</h3>
<button onClick={() => navigateToFoo({ name: "jack" })}>Go to Foo</button>
</div>
);
}