keepContact项目
郭旭升 Lv6

技术点

browser router 客户端路由

  • createBrowserRouter
    使用 DOM History API来更新URL和管理历史堆栈。同时还允许使用 loaders, actions, fetchers等。

  • 客户端路由
    客户端路由可以不用从服务端请求一个新文件来更新URL,app可以快速的渲染新的UI。
    Client side routing allows our app to update the URL without requesting another document from the server. Instead, the app can immediately render new UI. Let’s make it happen with .

error page

当渲染、加载、更改数据时抛出错误是,reactrouter都会捕捉,渲染一个错误页面。
Anytime your app throws an error while rendering, loading data, or performing data mutations, React Router will catch it and render an error screen.
可以创建自己的error page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { useRouteError } from "react-router-dom";

export default function ErrorPage() {
const error = useRouteError();
console.error(error);

return (
<div id="error-page">
<h1>Oops!</h1>
<p>Sorry, an unexpected error has occurred.</p>
<p>
<i>{error.statusText || error.message}</i>
</p>
</div>
);
}

然后再main.jsx中添加这个errorpage

1
2
3
4
5
6
7
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
errorElement: <ErrorPage />,
},
]);

HTML表单会触发导航,就像点击了一个链接。 区别是, 链接只会改变URL,而表单还会改变请求方法和请求体。

如果没有客户端导航,浏览器会自动序列化表单数据发送请求, 要么作为post方式的请求体,或者get方式的URL搜索变量。 react router做同样的事情, 但是不会将请求发送给服务端,而是使用客户端导航,把数据发送给路由的‘action’。

HTML forms actually cause a navigation in the browser, just like clicking a link. The only difference is in the request: links can only change the URL while forms can also change the request method (GET vs POST) and the request body (POST form data).

Without client side routing, the browser will serialize the form’s data automatically and send it to the server as the request body for POST, and as URLSearchParams for GET. React Router does the same thing, except instead of sending the request to the server, it uses client side routing and sends it to a route action.

 Comments