react-router新手教程学习笔记

发表于:2023-07-27 09:27
技术,react
热度:93
喜欢:0

安装

复制代码
pnpm add react-router-dom -D 

使用

tsx 复制代码
import { createBrowserRouter, RouterProvider } from "react-router-dom";
const router = createBrowserRouter([
  {
    path: "/",
    element: <Root />,
    errorElement: <ErrorPage />,
    loader: rootLoader,
    action: rootAction,
    children: [
      {
        path: "contacts/:contactId",
        loader: contactLoader,
        element: <Contact />,
      },
      {
        path: "contacts/:contactId/edit",
        element: <EditContact />,
        loader: contactLoader,
        action: EditAction,
      },
    ],
  },
]);

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);

root.render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

Loader

loader理解为加载页面的请求

typescript 复制代码
interface LoaderFunctionArgs {
    request: Request;
    params: Params;
    context?: any;
}
export async function loader({ params }: LoaderFunctionArgs) {
  const contact = await getContact(params.contactId);
  return { contact };
}

action

理解为post请求该页面的时候,处理方式行为

Form

行为与普通表单类似,只是与服务器的交互是使用fetch而不是新的文档请求,允许组件在表单提交并返回时向页面添加更好的用户体验

html 复制代码
<Form
  method="post"
  action="destroy"
  onSubmit={(event) => {
     event.preventDefault();
  }}
>
  <button type="submit">Delete</button>
</Form>
编译到DOM里面变成了

```html
<form action="/contacts/fhv3v52/destroy" method="post">
</form>

类似于<router-link >标签,有to属性

除了to属性,className、children、style可以返回{isActive,isPending}

tsx 复制代码
<NavLink
    to={`contacts/${contact.id}`}
    className={({ isActive, isPending }) =>
      isActive
        ? "active"
        : isPending
        ? "pending"
        : ""
    }
  >
  </NavLink>

useNavigation

useNavigation returns the current navigation state: it can be one of "idle" | "submitting" | "loading".

复制代码
const navigation = useNavigation();
navigation.state = '限制' | '提交中' | '加载中'

useSubmit

模拟提交

复制代码
<input
  id="q"
  aria-label="Search contacts"
  placeholder="Search"
  type="search"
  name="q"
  value={query}
  onChange={(e) => {
    setQuery(e.target.value);
    submit(e.currentTarget.form);
  }}
/>