|
|
|
|
|
|
|
|
|
|
|
|
|
|
'use client';
import { useRouter } from 'next/navigation';
export default function Page() {
const router = useRouter();
return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
useRouter 提供了 push() 、refresh() 等方法。有关详细信息,请参阅 API 参考。
建议:使用 <Link> 组件在路由之间导航,除非您有使用 useRouter 的特定要求。
导航的工作原理
使用<Link> 或调用 router.push() 启动路由转换。
路由器更新浏览器地址栏中的 URL。
路由器通过重新使用客户端缓存中未更改的段(例如共享布局)来避免不必要的工作。这也称为部分渲染。
如果满足软导航的条件,则路由器从缓存而不是服务器中获取新段。如果不是,路由器将执行硬导航并从服务器获取服务器组件有效负载。
如果已创建,则会在获取有效负载时从服务器显示加载 UI。
路由器使用缓存的或新的有效负载在客户端上呈现新的段。
[Client-side Caching of Rendered Server Components]
渲染服务器组件的客户端缓存
提示:此客户端缓存不同于服务器端 Next.js HTTP 缓存
新路由器有一个内存中的客户端缓存,用于存储服务器组件(有效负载)的渲染结果。缓存按路由段拆分,允许在任何级别失效并确保并发渲染之间的一致性。
当用户在应用程序中导航时,路由器会将先前获取的段和预取段的有效负载存储在缓存中。
这意味着,在某些情况下,路由器可以重新使用缓存而不是向服务器发出新请求。这通过避免不必要地重新获取数据和重新渲染组件来提高性能。
使缓存失效
服务器操作可用于通过路径 revalidatePath 或缓存标记 revalidateTag 按需重新验证数据。
预取是一种在访问路由之前在后台预加载路由的方法。预取路由的渲染结果被添加到路由器的客户端缓存中。这使得导航到预取路线近乎即时。
默认情况下,当使用<Link> 组件时,路由在viewport中可见时会被预取。这可能会在页面首次加载或滚动时发生。也可以使用useRouter() hook的预取方法以编程方式预取路由。
静态和动态路由:
如果路由是静态的,路由段的所有服务器组件负载都将被预取。
如果路由是动态的,则预取从第一个共享布局到第一个 loading.js 文件的有效负载。这降低了动态预取整个路由的成本,并允许动态路由的即时加载状态 。
预取仅在生产中启用。
可以通过将 prefetch={false} 传递给<Link> 来禁用预取。
硬导航
在导航时,缓存失效,服务器重新获取数据并重新呈现更改的段。
在导航时,更改段的缓存将被重用(如果存在),并且不会向服务器发出新的数据请求。
软导航的条件
在导航方面,如果您导航到的路线已被预取,并且不包含动态段或具有与当前路线相同的动态参数,则 Next.js 将使用软导航。
例如,考虑以下包含动态 [team] 段的路由:/dashboard/[team]/* 。 当[team] 参数发生变化时/dashboard/[team]/* 之下面的缓存段失效。
- 从 /dashboard/team-red/* 导航到 /dashboard/team-red/* 将是一个软导航。
- 从 /dashboard/team-red/* 导航到 /dashboard/team-blue/* 将是硬导航。
后退/前进导航
前后导航popstate event事件具有软导航行为。这意味着,客户端缓存被重新使用,导航几乎是即时的。
可以通过将文件夹名称括在括号中来创建路由组:(folderName)
在不影响 URL 路径的情况下组织路由
要在不影响 URL 的情况下组织路由,请创建一个组以将相关路由放在一起。括号中的文件夹将从 URL 中省略(例如 (marketing) 或 (shop) )。
即使 (marketing) 和 (shop) 中的路由共享相同的 URL 层次结构,您也可以通过在其文件夹中添加 layout.js 文件来为每个组创建不同的布局。
要将特定路线选择到布局中,请创建一个新路线组(例如(shop) )并将共享相同布局的路线移动到该组中(例如 account and cart )。组外的路线不会共享布局(例如checkout )。
要创建多个根布局,请删除顶级 layout.js 文件,并在每个路由组中添加一个 layout.js 文件。这对于将应用程序划分为具有完全不同的 UI 或体验的部分非常有用。<html> 和<body> 标签需要添加到每个根布局。
路由组的命名除了组织之外没有特殊意义。它们不影响 URL 路径。
路由组内的路由不应解析为相同的 URL 路径。例如,由于路由组不影响 URL 结构,(marketing)/about/page.js 和 (shop)/about/page.js 都会解析为 /about 并导致错误。
跨多个根布局导航将导致整个页面加载(与客户端导航相反)。例如,从使用 app/(shop)/layout.js 的 /cart 导航到使用 app/(marketing)/layout.js 的 /blog 将导致整个页面加载。这仅适用于多根布局。
动态路由
当您事先不知道确切的路段名称并希望从动态数据创建路线时,您可以使用在请求时填写或在构建时prerendered的动态路段。
可以通过将文件夹名称括在方括号中来创建动态细分:[folderName] 。例如,[id] 或[slug] 。
动态细分作为 params 属性传递给布局、页面、路由和generateMetadata 。
例如,博客可以包含以下路由 app/blog/[slug]/page.js ,其中 [slug] 是博客文章的动态部分。
app/blog/[slug]/page.tsx
3
|
|
|
export default function Page({ params }: { params: { slug: string } }) {
return <h1>My Page</h1>
Route | params Type Definition |
---|
app/blog/[slug]/page.js | { slug: string } | app/shop/[...slug]/page.js | { slug: string[] } | app/[categoryId]/[itemId]/page.js | { categoryId: string, itemId: string } |
注意:这可能会在未来由 TypeScript 插件自动完成。
加载 UI 和流式传输
The special file loading.js helps you create meaningful Loading UI with React Suspense. With this convention, you can show an instant loading state from the server while the content of a route segment loads, the new content is automatically swapped in once rendering is complete.
特殊文件 loading.js 可帮助您使用 React Suspense 创建有意义的加载 UI
.使用此约定,您可以在加载路由段的内容时显示来自服务器的即时加载状态,一旦渲染完成,新内容将自动交换。
即时加载状态
An instant loading state is fallback UI that is shown immediately upon navigation. You can pre-render loading indicators such as skeletons and spinners, or a small but meaningful part of future screens such as a cover photo, title, etc. This helps users understand the app is responding and provides a better user experience.
即时加载状态是在导航时立即显示的回退 UI。您可以预渲染加载指示器,如骨架和微调器,或未来屏幕的一小部分但有意义的部分,如封面照片、标题等。这有助于用户了解应用程序正在响应并提供更好的用户体验。
Create a loading state by adding a loading.js file inside a folder.
通过在文件夹中添加 loading.js 文件来创建加载状态。
app/dashboard/loading.tsx
4
|
export default function Loading() {
// You can add any UI inside Loading, including a Skeleton.
return <LoadingSkeleton />;
In the same folder, loading.js will be nested inside layout.js . It will automatically wrap the page.js file and any children below in a <Suspense> boundary.
在同一文件夹中,loading.js 将嵌套在 layout.js 中。它会自动将 page.js 文件和下面的任何子文件包装在 边界中。
Good to know:
很高兴知道:
Navigation is immediate, even with server-centric routing.
导航是即时的,即使使用以服务器为中心的路由也是如此。
Navigation is interruptible, meaning changing routes does not need to wait for the content of the route to fully load before navigating to another route.
导航是可中断的,这意味着更改路线不需要等待路线内容完全加载后再导航到另一条路线。
Shared layouts remain interactive while new route segments load.
共享布局在加载新路线段时保持交互。
Recommendation: Use the loading.js convention for route segments (layouts and pages) as Next.js optimizes this functionality.
建议:对路由段(布局和页面)使用 loading.js 约定,因为 Next.js 优化了此功能。
In addition to loading.js , you can also manually create Suspense Boundaries for your own UI components. The App Router supports streaming with Suspense for both Node.js and Edge runtimes.
除了 loading.js 之外,您还可以为自己的 UI 组件手动创建 Suspense Boundaries。 App Router 支持使用 Suspense 进行流式传输 适用于 Node.js 和 Edge 运行时。
什么是流媒体?
To learn how Streaming works in React and Next.js, it's helpful to understand Server-Side Rendering (SSR) and its limitations.
要了解 Streaming 在 React 和 Next.js 中的工作原理,了解服务器端渲染 (SSR) 及其局限性很有帮助。
With SSR, there's a series of steps that need to be completed before a user can see and interact with a page:
使用 SSR,在用户可以查看页面并与之交互之前需要完成一系列步骤:
First, all data for a given page is fetched on the server.
首先,在服务器上获取给定页面的所有数据。
The server then renders the HTML for the page.
然后服务器呈现页面的 HTML。
The HTML, CSS, and JavaScript for the page are sent to the client.
页面的 HTML、CSS 和 JavaScript 被发送到客户端。
A non-interactive user interface is shown using the generated HTML, and CSS.
使用生成的 HTML 和 CSS 显示非交互式用户界面。
Finally, React hydrates the user interface to make it interactive.
最后,React 水合物 用户界面,使其具有交互性。
These steps are sequential and blocking, meaning the server can only render the HTML for a page once all the data has been fetched. And, on the client, React can only hydrate the UI once the code for all components in the page has been downloaded.
这些步骤是顺序的和阻塞的,这意味着服务器只能在获取所有数据后才能呈现页面的 HTML。而且,在客户端,React 只能在页面中所有组件的代码都已下载后才能对 UI 进行水合。
SSR with React and Next.js helps improve the perceived loading performance by showing a non-interactive page to the user as soon as possible.
使用 React 和 Next.js 的 SSR 通过尽快向用户显示非交互式页面来帮助提高感知加载性能。
However, it can still be slow as all data fetching on server needs to be completed before the page can be shown to the user.
但是,它仍然可能很慢,因为需要在页面显示给用户之前完成服务器上的所有数据获取。
Streaming allows you to break down the page's HTML into smaller chunks and progressively send those chunks from the server to the client.
Streaming 允许您将页面的 HTML 分解为更小的块,并逐步将这些块从服务器发送到客户端。
This enables parts of the page to be displayed sooner, without waiting for all the data to load before any UI can be rendered.
这使得部分页面能够更快地显示,而无需等待所有数据加载完毕才能呈现任何 UI。
Streaming works well with React's component model because each component can be considered a chunk. Components that have higher priority (e.g. product information) or that don't rely on data can be sent first (e.g. layout), and React can start hydration earlier. Components that have lower priority (e.g. reviews, related products) can be sent in the same server request after their data has been fetched.
Streaming 与 React 的组件模型配合得很好,因为每个组件都可以被视为一个块。优先级较高的组件(例如产品信息)或不依赖数据的组件可以先发送(例如布局),React 可以更早地开始水合。具有较低优先级的组件(例如评论、相关产品)可以在获取数据后在同一服务器请求中发送。
Streaming is particularly beneficial when you want to prevent long data requests from blocking the page from rendering as it can reduce the Time To First Byte (TTFB) and First Contentful Paint (FCP). It also helps improve Time to Interactive (TTI), especially on slower devices.
当您想要防止长数据请求阻止页面呈现时,流式处理特别有用,因为它可以减少首字节时间 (TTFB) 和第一内容绘画(FCP) 它还有助于改善交互时间 (TTI) ,尤其是在速度较慢的设备上。
<Suspense> works by wrapping a component that performs an asynchronous action (e.g. fetch data), showing fallback UI (e.g. skeleton, spinner) while it's happening, and then swapping in your component once the action completes.
<Suspense> 的工作原理是包装一个执行异步操作(例如获取数据)的组件,在它发生时显示回退 UI(例如骨架、微调器),然后在操作完成后交换您的组件。
app/dashboard/page.tsx
14
|
|
'use client'; // Error components must be Client components
import { useEffect } from 'react';
export default function Error({
error,
reset,
error: Error;
reset: () => void;
useEffect(() => {
// Log the error to an error reporting service
console.error(error);
}, [error]);
return (
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
Try again
</button>
error.js 是如何工作的
error.js automatically creates an React Error Boundary that wraps a nested child segment or page.js component.
error.js 自动创建一个 React 错误边界包装嵌套的子段或 page.js 组件。
The React component exported from the error.js file is used as the fallback component.
从 error.js 文件导出的 React 组件用作回退组件。
If an error is thrown within the error boundary, the error is contained, and the fallback component is rendered.
如果在错误边界内抛出错误,则包含错误,并呈现回退组件。
When the fallback error component is active, layouts above the error boundary maintain their state and remain interactive, and the error component can display functionality to recover from the error.
当回退错误组件处于活动状态时,错误边界上方的布局会保持其状态并保持交互,并且错误组件可以显示从错误中恢复的功能。
从错误中恢复
The cause of an error can sometimes be temporary. In these cases, simply trying again might resolve the issue.
错误的原因有时可能是暂时的。在这些情况下,只需重试即可解决问题。
An error component can use the reset() function to prompt the user to attempt to recover from the error. When executed, the function will try to re-render the Error boundary's contents. If successful, the fallback error component is replaced with the result of the re-render.
错误组件可以使用 reset() 函数来提示用户尝试从错误中恢复。执行时,该函数将尝试重新呈现错误边界的内容。如果成功,回退错误组件将替换为重新渲染的结果。
app/dashboard/error.ts
15
|
'use client';
export default function Error({
error,
reset,
error: Error;
reset: () => void;
return (
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
React components created through special files are rendered in a specific nested hierarchy.
通过特殊文件创建的 React 组件在特定的嵌套层次结构中呈现。
For example, a nested route with two segments that both include layout.js and error.js files are rendered in the following simplified component hierarchy:
例如,包含两个段的嵌套路由都包含 layout.js 和 error.js 文件,在以下简化的组件层次结构中呈现:
The nested component hierarchy has implications for the behavior of error.js files across a nested route:
嵌套组件层次结构对跨嵌套路由的 error.js 文件的行为有影响:
Errors bubble up to the nearest parent error boundary. This means an error.js file will handle errors for all its nested child segments. More or less granular error UI can be achieved by placing error.js files at different levels in the nested folders of a route.
错误冒泡到最近的父错误边界。这意味着 error.js 文件将处理其所有嵌套子段的错误。通过将 error.js 文件放置在路由的嵌套文件夹中的不同级别,可以实现或多或少的粒度错误 UI。
An error.js boundary will not handle errors thrown in a layout.js component in the same segment because the error boundary is nested inside that layouts component.
error.js 边界不会处理同一段中 layout.js 组件中抛出的错误,因为错误边界嵌套在该布局组件内。
处理布局中的错误
error.js boundaries do not catch errors thrown in layout.js or template.js components of the same segment. This intentional hierarchy keeps important UI that is shared between sibling routes (such as navigation) visible and functional when an error occurs.
error.js 边界不会捕获在同一段的 layout.js 或 template.js 组件中抛出的错误。当发生错误时,这种有意的层次结构使兄弟路由(例如导航)之间共享的重要 UI 保持可见和正常运行。
To handle errors within a specific layout or template, place an error.js file in the layouts parent segment.
要处理特定布局或模板中的错误,请将 error.js 文件放在布局父段中。
To handle errors within the root layout or template, use a variation of error.js called global-error.js .
要处理根布局或模板中的错误,请使用称为 global-error.js 的 error.js 变体。
处理根布局中的错误
根 app/error.js 边界不会捕获根 app/layout.js 或 app/template.js 组件中抛出的错误。
要专门处理这些根组件中的错误,请使用位于应用程序根目录中的名为 app/global-error.js 的 error.js 变体。
与根 error.js 不同,global-error.js 错误边界包裹了整个应用程序,其回退组件在活动时替换根布局。因此,请务必注意 global-error.js 必须定义自己的<html> 和<body> 标签。
global-error.js 是最小粒度的错误 UI,可以被认为是整个应用程序的“包罗万象catch-all”的错误处理。它不太可能经常被触发,因为根组件通常不太动态,并且其他 error.js 边界会捕获大多数错误。
即使定义了 global-error.js ,仍然建议定义一个根 error.js ,其回退组件将在根布局中呈现,其中包括全局共享的 UI 和品牌。
app/global-error.tsx
17
|
|