pnpm add react-router-dom -D
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理解为加载页面的请求
interface LoaderFunctionArgs {
request: Request;
params: Params;
context?: any;
}
export async function loader({ params }: LoaderFunctionArgs) {
const contact = await getContact(params.contactId);
return { contact };
}
理解为post请求该页面的时候,处理方式行为
行为与普通表单类似,只是与服务器的交互是使用fetch而不是新的文档请求,允许组件在表单提交并返回时向页面添加更好的用户体验
<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}
<NavLink
to={`contacts/${contact.id}`}
className={({ isActive, isPending }) =>
isActive
? "active"
: isPending
? "pending"
: ""
}
>
</NavLink>
useNavigation returns the current navigation state: it can be one of "idle" | "submitting" | "loading".
const navigation = useNavigation();
navigation.state = '限制' | '提交中' | '加载中'
模拟提交
<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);
}}
/>