revalidatePath
revalidatePath
允许你按需清除特定路径的缓存数据。
须知:
参数
revalidatePath(path: string, type?: 'page' | 'layout'): void;
path
:一个字符串,表示与要重新验证的数据关联的文件系统路径(例如,/product/[slug]/page
),或字面路由段(例如,/product/123
)。必须少于 1024 个字符。此值区分大小写。type
:(可选)'page'
或'layout'
字符串,用于更改要重新验证的路径类型。如果path
包含动态段(例如,/product/[slug]/page
),则此参数是必需的。如果路径引用字面路由段,例如,动态页面(例如,/product/[slug]/page
)的/product/1
,则不应提供type
。
返回值
revalidatePath
不返回值。
示例
重新验证特定 URL
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/post-1')
这将在下次页面访问时重新验证一个特定的 URL。
重新验证页面路径
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/[slug]', 'page')
// or with route groups
revalidatePath('/(main)/blog/[slug]', 'page')
这将在下次页面访问时重新验证任何与提供的 page
文件匹配的 URL。这将不会使特定页面下方的页面失效。例如,/blog/[slug]
不会使 /blog/[slug]/[author]
失效。
重新验证布局路径
import { revalidatePath } from 'next/cache'
revalidatePath('/blog/[slug]', 'layout')
// or with route groups
revalidatePath('/(main)/post/[slug]', 'layout')
这将在下次页面访问时重新验证任何与提供的 layout
文件匹配的 URL。这将导致具有相同布局的下方页面在下次访问时重新验证。例如,在上述情况下,/blog/[slug]/[another]
也将在下次访问时重新验证。
重新验证所有数据
import { revalidatePath } from 'next/cache'
revalidatePath('/', 'layout')
这将清除客户端路由器缓存,并在下次页面访问时重新验证数据缓存。
服务器操作
app/actions.ts
'use server'
import { revalidatePath } from 'next/cache'
export default async function submit() {
await submitForm()
revalidatePath('/')
}
路由处理程序
app/api/revalidate/route.ts
import { revalidatePath } from 'next/cache'
import type { NextRequest } from 'next/server'
export async function GET(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path')
if (path) {
revalidatePath(path)
return Response.json({ revalidated: true, now: Date.now() })
}
return Response.json({
revalidated: false,
now: Date.now(),
message: 'Missing path to revalidate',
})
}
这篇文章对您有帮助吗?