Skip to content

Latest commit

 

History

History
88 lines (68 loc) · 2.17 KB

README.zh.md

File metadata and controls

88 lines (68 loc) · 2.17 KB

English | 中文

react-typesafe-router

在 React.js 中定义完全类型安全的路由最简单的方式,你只需要使用 3 个 api。Vue3 版本在这里 (https://github.com/qinjialei24/vue-typesafe-router).

1726114162133

使用方法

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>
  );
}

现在,您可以传递类型安全的路由查询数据!

img.png

获取类型安全的路由查询数据

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>
  );
}

现在,您可以获取类型安全的路由查询数据! img_1.png