template.js
模板文件与 layout 类似,它封装布局或页面。与跨路由持续存在并维护状态的布局不同,模板被赋予一个唯一的键,这意味着子客户端组件在导航时重置其状态。
¥A template file is similar to a layout in that it wraps a layout or page. Unlike layouts that persist across routes and maintain state, templates are given a unique key, meaning children Client Components reset their state on navigation.
它们在以下情况下非常有用:
¥They are useful when you need to:
导航时重新同步
useEffect
。¥Resynchronize
useEffect
on navigation.导航时重置子客户端组件的状态。例如,一个输入字段。
¥Reset the state of a child Client Components on navigation. For example, an input field.
更改默认框架行为。例如,布局内的 Suspense 边界仅在首次加载时显示回退,而模板会在每次导航时显示回退。
¥To change default framework behavior. For example, Suspense boundaries inside layouts only show a fallback on first load, while templates show it on every navigation.
惯例
¥Convention
可以通过从 template.js
文件导出默认的 React 组件来定义模板。该组件应该接受 children
属性。
¥A template can be defined by exporting a default React component from a template.js
file. The component should accept a children
prop.

export default function Template({ children }: { children: React.ReactNode }) {
return <div>{children}</div>
}
在嵌套方面,template.js
在布局及其子布局之间渲染。这是一个简化的输出:
¥In terms of nesting, template.js
is rendered between a layout and its children. Here's a simplified output:
属性
¥Props
children
(必需的)
¥children
(required)
模板接受 children
属性。
¥Template accepts a children
prop.
行为
¥Behavior
服务器组件:默认情况下,模板是服务器组件。
¥Server Components: By default, templates are Server Components.
导航时重新挂载:模板会自动接收一个唯一键。导航到新路由会导致模板及其子模板重新挂载。
¥Remount on navigation: Templates receive a unique key automatically. Navigating to a new route causes the template and its children to remount.
状态重置:模板内的任何客户端组件都会在导航时重置其状态。
¥State reset: Any Client Component inside the template will reset its state on navigation.
重新运行效果:像
useEffect
这样的效果将在组件重新挂载时重新同步。¥Effect re-run: Effects like
useEffect
will re-synchronize as the component remounts.DOM 重置:模板内的 DOM 元素将被完全重新创建。
¥DOM reset: DOM elements inside the template are fully recreated.
版本历史
¥Version History
版本 | 更改 |
---|---|
v13.0.0 | template 已引入。 |