如何使用 Next.js 构建单页应用
Next.js 完全支持构建单页应用(SPA)。
使用客户端导航和数据获取构建单页应用(SPA)。Next.js 在同一个应用中同时支持客户端和服务端模式,现有 SPA 无需完全重写即可迁移。
什么是单页应用?#
SPA 的定义各不相同。我们将"严格 SPA"定义为:
- 客户端渲染(Client-side rendering,CSR):应用由单个 HTML 文件(例如
index.html)提供。每个路由、页面切换和数据获取都由浏览器中的 JavaScript 处理。 - 无整页刷新:客户端 JavaScript 不会为每个路由请求新文档,而是操作当前页面的 DOM 并按需获取数据。
严格 SPA 通常需要在页面可交互之前加载大量 JavaScript。此外,客户端数据瀑布流可能难以管理。使用 Next.js 构建 SPA 可以解决这些问题。
为什么使用 Next.js 构建 SPA?#
Next.js 可以自动对 JavaScript 包进行代码拆分,并为不同路由生成多个 HTML 入口点。这避免了在客户端加载不必要的 JavaScript 代码,减小了包体积并实现了更快的页面加载。
next/link 组件会自动预取路由,为你带来严格 SPA 的快速页面切换,同时还具有将应用路由状态保留到 URL 中以便于链接和分享的优势。
Next.js 可以从静态站点甚至严格 SPA(所有内容都在客户端渲染)开始。如果项目不断发展,你可以按需逐步添加更多服务端功能(例如 React Server Components、Server Actions 等)。
构建常见 SPA 模式#
以下示例涵盖了使用 Next.js 构建 SPA 的常见模式。配套的演示(源码)展示了每种模式的实际运行效果。
在 Context Provider 中使用 React 的 use#
你可以使用 React 的 use API 将数据从服务端流式传输到 Client Component。在 Server Component(父组件或布局)中获取数据并向下传递 Promise。Client Component 使用 use() 解包它,因为它无法在渲染期间 await。
在服务端发起请求(在应用其余部分渲染之前)可让响应立即开始流式传输,并避免客户端请求瀑布流。
你可以将单个 Promise 作为 prop 传递并用 use() 解包,也可以将其与 React context provider 配对,以便任何 Client Component 都能通过自定义 hook 读取该值。
当 Client Component 需要聚焦重新验证、轮询、变更或请求去重时,可使用 SWR 或 TanStack Query 等库。有关直接从浏览器获取数据、从 Server Component 提供初始数据以及协调库缓存与 Next.js 服务端和客户端缓存的内容,请参阅客户端数据获取。
在 Server Component(此处为根布局)中发起请求但不要等待它,然后将 Promise 传递给 provider:
import { UserProvider } from './user-provider'
import { getUser } from './user' // 某个服务端函数
export default function RootLayout({ children }: LayoutProps<'/'>) {
let userPromise = getUser() // 不要 await
return (
<html lang="en">
<body>
<UserProvider userPromise={userPromise}>{children}</UserProvider>
</body>
</html>
)
}import { UserProvider } from './user-provider'
import { getUser } from './user' // 某个服务端函数
export default function RootLayout({ children }) {
let userPromise = getUser() // 不要 await
return (
<html lang="en">
<body>
<UserProvider userPromise={userPromise}>{children}</UserProvider>
</body>
</html>
)
}小知识: 重新获取在组件树较高位置设置的 Promise 会重新运行设置它的 Server Component,因此对于只有部分应用需要的数据,请将 provider 放在该子树上,而不是根布局中。请参阅 React 关于从 context 读取 Promise 的注意事项。
如果多个组件在一次请求中读取相同的数据,请将 getUser 包装在 React 的 cache 中,以便它们共享一次调用。有关此模式的更多信息,请参阅使用 React.cache 复用数据。
provider 通过 context 转发 Promise:
'use client'
import { createContext, useContext } from 'react'
type User = { id: string; name: string }
const UserContext = createContext<Promise<User> | null>(null)
export function useUser() {
const userPromise = useContext(UserContext)
if (!userPromise) {
throw new Error('useUser must be used within a UserProvider')
}
return userPromise
}
export function UserProvider({
children,
userPromise,
}: {
children: React.ReactNode
userPromise: Promise<User>
}) {
return (
<UserContext.Provider value={userPromise}>{children}</UserContext.Provider>
)
}'use client'
import { createContext, useContext } from 'react'
const UserContext = createContext(null)
export function useUser() {
const userPromise = useContext(UserContext)
if (!userPromise) {
throw new Error('useUser must be used within a UserProvider')
}
return userPromise
}
export function UserProvider({ children, userPromise }) {
return (
<UserContext.Provider value={userPromise}>{children}</UserContext.Provider>
)
}最后,在任何 Client Component 中调用 useUser() hook 并用 use() 解包 Promise,这会使组件挂起直到数据就绪:
'use client'
import { use } from 'react'
import { useUser } from './user-provider'
export function Profile() {
const userPromise = useUser()
const user = use(userPromise)
return <p>{user.name}</p>
}'use client'
import { use } from 'react'
import { useUser } from './user-provider'
export function Profile() {
const userPromise = useUser()
const user = use(userPromise)
return <p>{user.name}</p>
}将消费者包裹在 <Suspense> 边界中,以便在 Promise 解析期间显示回退内容:
import { Suspense } from 'react'
import { Profile } from './profile'
export default function Page() {
return (
<Suspense fallback={<p>Loading…</p>}>
<Profile />
</Suspense>
)
}import { Suspense } from 'react'
import { Profile } from './profile'
export default function Page() {
return (
<Suspense fallback={<p>Loading…</p>}>
<Profile />
</Suspense>
)
}使用 Promise 的组件(例如上面的 Profile)会在 Promise 解析期间挂起,因此你可以在 JavaScript 完成加载之前看到流式传输的预渲染 HTML。
仅在浏览器中渲染组件#
Client Component 会在 next build 期间被预渲染。如果你想禁用某个 Client Component 的预渲染,仅在浏览器环境中加载它,可以使用 next/dynamic:
import dynamic from 'next/dynamic'
const ClientOnlyComponent = dynamic(() => import('./component'), {
ssr: false,
})这对于依赖 window 或 document 等浏览器 API 的第三方库很有用。你还可以添加一个 useEffect 来检查这些 API 是否存在,如果不存在,则返回 null 或将被预渲染的加载状态。
React 19.3 包含 browser API。仅当 Client Component 的首次浏览器渲染无法与服务端渲染的 HTML 匹配时,才使用 use(browser())。
在预渲染期间,use(browser()) 会挂起到最近的 <Suspense> 边界。回退内容将成为组件的初始 HTML,因此不执行 JavaScript 的爬虫看到的将是回退内容而不是组件。请将需要被索引的内容放在仅限浏览器的边界之外。
例如,这个编辑器从 localStorage 读取保存的草稿:
'use client'
import { use, useState } from 'react'
import { browser } from 'react-dom'
export default function BrowserOnlyEditor() {
use(browser('The saved draft is stored in localStorage.'))
const [draft, setDraft] = useState(() => localStorage.getItem('draft') ?? '')
function handleChange(event) {
const nextDraft = event.target.value
setDraft(nextDraft)
localStorage.setItem('draft', nextDraft)
}
return <textarea value={draft} onChange={handleChange} />
}然后将其包裹在 Suspense 边界中:
import { Suspense } from 'react'
import BrowserOnlyEditor from './browser-only-editor'
export default function Page() {
return (
<Suspense fallback={<p>Loading editor…</p>}>
<BrowserOnlyEditor />
</Suspense>
)
}在浏览器中,browser() 返回 undefined,编辑器会使用保存的草稿进行渲染。
客户端浅层路由#
如果你正在从 Create React App 或 Vite 等严格 SPA 迁移,可能已有使用浅层路由来更新 URL 状态的代码。在不使用 Next.js 默认文件系统路由的情况下,这对于在应用中的视图之间手动切换很有用。
Next.js 允许你使用原生的 window.history.pushState 和 window.history.replaceState 方法来更新浏览器的历史记录栈,而无需重新加载页面。
Next.js 将 pushState 和 replaceState 调用集成到路由器中,因此使用 usePathname 或 useSearchParams 渲染的组件会在 URL 变化时更新。当事件处理器是组件唯一需要 URL 的地方时,请在处理器中读取 window.location,而不要调用 usePathname 或 useSearchParams。这两个 hook 都会影响预渲染。
'use client'
export default function SortProducts() {
function updateSorting(sortOrder: string) {
const urlSearchParams = new URLSearchParams(window.location.search)
urlSearchParams.set('sort', sortOrder)
window.history.pushState(null, '', `?${urlSearchParams.toString()}`)
}
return (
<>
<button onClick={() => updateSorting('asc')}>Sort Ascending</button>
<button onClick={() => updateSorting('desc')}>Sort Descending</button>
</>
)
}'use client'
export default function SortProducts() {
function updateSorting(sortOrder) {
const urlSearchParams = new URLSearchParams(window.location.search)
urlSearchParams.set('sort', sortOrder)
window.history.pushState(null, '', `?${urlSearchParams.toString()}`)
}
return (
<>
<button onClick={() => updateSorting('asc')}>Sort Ascending</button>
<button onClick={() => updateSorting('desc')}>Sort Descending</button>
</>
)
}详细了解 Next.js 中的路由和导航如何工作。
使用 Server Actions 修改数据#
交互通常需要写入数据。Client Component 可以调用 Server Action 在服务端执行变更操作。客户端数据获取库可以围绕同一个 Server Action 协调乐观的浏览器更新,如客户端数据获取指南中所示。本节其余部分将介绍如何将该 Server Action 与 React 内置的状态 API 配合使用。
Server Action 需要时间且可能失败。React 提供了一些有用的工具,可在其运行时保持 UI 响应,使变更操作感觉像客户端渲染的 SPA 一样即时:transitions、useOptimistic、useActionState 和 useFormStatus。
最简单的形式是,Client Component 在 transition 中调用 Server Action,并使用 pending 状态提供反馈:
'use client'
import { useTransition } from 'react'
import { deletePost } from './actions'
export function DeletePost({ id }: { id: string }) {
const [isPending, startTransition] = useTransition()
return (
<button
disabled={isPending}
onClick={() => startTransition(() => deletePost(id))}
>
{isPending ? 'Deleting…' : 'Delete'}
</button>
)
}'use client'
import { useTransition } from 'react'
import { deletePost } from './actions'
export function DeletePost({ id }) {
const [isPending, startTransition] = useTransition()
return (
<button
disabled={isPending}
onClick={() => startTransition(() => deletePost(id))}
>
{isPending ? 'Deleting…' : 'Delete'}
</button>
)
}对于每项更改都应立即显示的列表类状态,你可以将 useActionState 与 useOptimistic 结合使用。下面的示例是一个待办事项列表:一个纯 reducer 定义了每个 action 如何更改列表,因此客户端和服务端共享该逻辑的一份副本:
export type Todo = { id: string; text: string; done: boolean }
export type TodoAction =
| { type: 'add'; id: string; text: string }
| { type: 'toggle'; id: string }
| { type: 'edit'; id: string; text: string }
| { type: 'delete'; id: string }
export function todosReducer(todos: Todo[], action: TodoAction): Todo[] {
switch (action.type) {
case 'add':
return [...todos, { id: action.id, text: action.text, done: false }]
case 'toggle':
return todos.map((todo) =>
todo.id === action.id ? { ...todo, done: !todo.done } : todo
)
case 'edit':
return todos.map((todo) =>
todo.id === action.id ? { ...todo, text: action.text } : todo
)
case 'delete':
return todos.filter((todo) => todo.id !== action.id)
default:
return todos
}
}export function todosReducer(todos, action) {
switch (action.type) {
case 'add':
return [...todos, { id: action.id, text: action.text, done: false }]
case 'toggle':
return todos.map((todo) =>
todo.id === action.id ? { ...todo, done: !todo.done } : todo
)
case 'edit':
return todos.map((todo) =>
todo.id === action.id ? { ...todo, text: action.text } : todo
)
case 'delete':
return todos.filter((todo) => todo.id !== action.id)
default:
return todos
}
}Server Action 应用 reducer、持久化结果并返回下一个列表:
'use server'
import { db } from './db'
import { todosReducer, type Todo, type TodoAction } from './todos-reducer'
export async function saveTodos(
todos: Todo[],
action: TodoAction
): Promise<Todo[]> {
const next = todosReducer(todos, action)
await db.saveTodos(next)
return next
}'use server'
import { db } from './db'
import { todosReducer } from './todos-reducer'
export async function saveTodos(todos, action) {
const next = todosReducer(todos, action)
await db.saveTodos(next)
return next
}客户端将同一个 reducer 传递给 useOptimistic,因此乐观更新和服务端以相同方式计算下一个状态。runAction 辅助函数会在同一个 transition 中应用乐观更改并派发 Server Action,因此每项更改都会立即显示:
'use client'
import { useActionState, useOptimistic, startTransition } from 'react'
import { saveTodos } from './actions'
import { todosReducer, type Todo, type TodoAction } from './todos-reducer'
export function TodoList({ initialTodos }: { initialTodos: Todo[] }) {
const [todos, dispatch, isPending] = useActionState(saveTodos, initialTodos)
const [optimisticTodos, addOptimistic] = useOptimistic(todos, todosReducer)
function runAction(action: TodoAction) {
startTransition(() => {
addOptimistic(action)
dispatch(action)
})
}
return (
<>
<form
action={(formData) =>
runAction({
type: 'add',
id: crypto.randomUUID(),
text: String(formData.get('text')),
})
}
>
<input name="text" />
<button>Add</button>
</form>
<ul>
{optimisticTodos.map((todo) => (
<li key={todo.id}>
<input
type="checkbox"
checked={todo.done}
onChange={() => runAction({ type: 'toggle', id: todo.id })}
/>
<span
style={{ textDecoration: todo.done ? 'line-through' : 'none' }}
>
{todo.text}
</span>
<button onClick={() => runAction({ type: 'delete', id: todo.id })}>
Delete
</button>
</li>
))}
</ul>
{isPending && <p>Syncing to server…</p>}
</>
)
}'use client'
import { useActionState, useOptimistic, startTransition } from 'react'
import { saveTodos } from './actions'
import { todosReducer } from './todos-reducer'
export function TodoList({ initialTodos }) {
const [todos, dispatch, isPending] = useActionState(saveTodos, initialTodos)
const [optimisticTodos, addOptimistic] = useOptimistic(todos, todosReducer)
function runAction(action) {
startTransition(() => {
addOptimistic(action)
dispatch(action)
})
}
return (
<>
<form
action={(formData) =>
runAction({
type: 'add',
id: crypto.randomUUID(),
text: String(formData.get('text')),
})
}
>
<input name="text" />
<button>Add</button>
</form>
<ul>
{optimisticTodos.map((todo) => (
<li key={todo.id}>
<input
type="checkbox"
checked={todo.done}
onChange={() => runAction({ type: 'toggle', id: todo.id })}
/>
<span
style={{ textDecoration: todo.done ? 'line-through' : 'none' }}
>
{todo.text}
</span>
<button onClick={() => runAction({ type: 'delete', id: todo.id })}>
Delete
</button>
</li>
))}
</ul>
{isPending && <p>Syncing to server…</p>}
</>
)
}乐观更新会立即显示,而 useActionState 的 pending 标志可让你在 Server Action 解析之前显示一个细微的指示器(例如 Syncing to server…)。
要了解如何在服务端渲染的应用之上添加交互性,使其感觉像 SPA,请参阅构建交互式应用指南及其可运行的演示。
静态导出(可选)#
Next.js 还支持生成完整的静态站点。与严格 SPA 相比,这有一些优势:
- 自动代码拆分:Next.js 不会只提供一个
index.html,而是为每个路由生成一个 HTML 文件,这样访问者无需等待客户端 JavaScript 包即可更快地获取内容。 - 改善用户体验:你无需为所有路由提供最小的骨架,而是为每个路由获得完整渲染的页面。当用户进行客户端导航时,切换仍然是即时的、类似 SPA 的。
要启用静态导出,请更新你的配置:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
output: 'export',
}
export default nextConfig运行 next build 后,Next.js 将创建一个 out 文件夹,其中包含应用的 HTML/CSS/JS 资源。
注意: 静态导出不支持 Next.js 服务端功能。了解更多。
将现有项目迁移到 Next.js#
你可以按照我们的指南逐步迁移到 Next.js:
如果你已经在使用基于 Pages Router 的 SPA,可以了解如何逐步采用 App Router。