修改数据与重新验证
学习服务器操作如何在服务器上修改数据,并自动重新验证缓存数据以更新用户界面
修改数据与重新验证 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is Data Mutation?
In web development, data mutation means changing data on the server. This includes creating new data, updating existing records, or deleting data.
- Create: Adding a new user.
- Update: Changing a user's email.
- Delete: Removing an item from a list.
Most interactive web applications rely heavily on data mutation to provide dynamic experiences.
Server Actions for Mutations
Next.js 15's Server Actions are perfect for handling data mutations. They allow you to run server-side code directly from your React components, making it simple to update your backend.
Instead of creating API routes for every data change, you can define these actions right where they're needed, keeping your code organized and efficient.
The Cache Challenge
When you mutate data on the server, the client-side UI often doesn't automatically reflect these changes. This is because Next.js (and browsers) aggressively cache data to improve performance.
If the UI still shows old, cached data after a server update, users see outdated information. We need a way to tell Next.js: "Hey, this data has changed, please get the fresh version!"
Revalidating with `revalidatePath`
To ensure your UI shows the latest data, Next.js provides caching utilities. One common method is revalidatePath.
After a Server Action changes data, you can call revalidatePath('/') to tell Next.js to invalidate the cache for the specified path (e.g., the home page) and refetch its data on the next request.
Demo: Update & Revalidate Path
This example shows a simple form that adds a task using a Server Action. After the task is added, revalidatePath('/') ensures that any data displayed on the root page (like a list of tasks) is refreshed.
import { revalidatePath } from 'next/cache';
async function addTask(formData) {
'use server';
const task = formData.get('task');
// Simulate saving to a database
console.log('Adding task:', task);
await new Promise(r => setTimeout(r, 500));
// Revalidate the home page to show new tasks
revalidatePath('/');
}
export default function Page() {
return (
<div>
<h1>My Task List</h1>
<form action={addTask}>
<input type="text" name="task" placeholder="New task" required />
<button type="submit">Add Task</button>
</form>
<p>Task list will refresh after adding!</p>
</div>
);
}Granular Control with `revalidateTag`
Sometimes you need more granular control over caching than just revalidating an entire path. This is where revalidateTag comes in.
When fetching data, you can assign a custom tag using the fetch API. Then, after a mutation, you can use revalidateTag('my-data-tag') to invalidate only the data associated with that specific tag.
When to use `revalidateTag`
Use revalidateTag when:
- Data is fetched from an external API using
fetch. - The data is shared across multiple pages or components.
- You want to update specific data without re-rendering entire pages.
It's ideal for scenarios like updating a single user's profile data that might appear on various pages.
Post-Mutation Redirection
After a successful data mutation, you often want to redirect the user to another page (e.g., a success page or the updated list page). Next.js provides a redirect helper for this.
You can use redirect('/dashboard') inside your Server Action to send the user to the dashboard after a form submission.
Full Flow: Mutate, Revalidate, Redirect
This example combines all concepts: a form submission triggers a Server Action, which mutates data, revalidates the relevant path, and then redirects the user to a confirmation page.
import { revalidatePath, redirect } from 'next/cache';
async function createPost(formData) {
'use server';
const title = formData.get('title');
const content = formData.get('content');
// Simulate saving new post to a DB
console.log('New Post:', { title, content });
await new Promise(r => setTimeout(r, 700));
revalidatePath('/posts'); // Revalidate the posts list page
redirect('/posts/success'); // Redirect to a success page
}
export default function NewPostPage() {
return (
<div>
<h1>Create New Post</h1>
<form action={createPost}>
<input type="text" name="title" placeholder="Title" required />
<textarea name="content" placeholder="Content" required />
<button type="submit">Publish Post</button>
</form>
</div>
);
}Quick Check on Revalidation
A Server Action successfully creates a new product and you want to update the product listing page (/products) and also ensure any cached data specifically tagged 'featured-products' is refreshed. Which revalidation methods should you use?
Recap: Mutate & Revalidate
Great job! You've learned how Server Actions are key to mutating data on the server. You also mastered how to keep your UI fresh:
- Use Server Actions for creating, updating, or deleting data.
- Employ
revalidatePathto refresh data for specific routes. - Utilize
revalidateTagfor fine-grained cache invalidation of taggedfetchrequests. - Use
redirectto guide users after a successful action.
This powerful combination ensures your Next.js applications are always showing accurate, up-to-date information.
常见问题解答
「修改数据与重新验证」课时是免费的吗?
是的 — 「修改数据与重新验证」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。
「修改数据与重新验证」这节课中我会学到什么?
学习服务器操作如何在服务器上修改数据,并自动重新验证缓存数据以更新用户界面 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「修改数据与重新验证」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 基础服务器操作表单
- 修改数据与重新验证
- 操作中的错误处理
- 使用服务器操作实现乐观界面与待处理状态