Logo
Section 1 / 6

Server Actions 基础

学习如何创建和使用 Server Actions,实现直接的服务器与客户端通信。

导入

Server Actions 基础

学习如何创建和使用 Server Actions,实现直接的服务器与客户端通信。

在客户端组件中使用内联 Server Action

1// app/components/AddToCartButton.js 2 3'use client'; 4 5export default function AddToCartButton({ productId }) { 6 async function addToCart() { 7 'use server'; 8 console.log(`Item added to cart: ${productId}`); 9 // 在真实应用中,你在这里更新数据库。 10 } 11 12 return ( 13 <button 14 onClick={() => addToCart()} 15 className="bg-blue-500 text-white p-2 rounded" 16 > 17 Add to Cart 18 </button> 19 ); 20}

定义可重用的 Server Action

1// app/lib/actions.js 2 3'use server'; 4 5// 模拟数据库 6const todos = ['Learn React']; 7 8export async function createTodo(formData) { 9 const newTodo = formData.get('todo'); 10 if (!newTodo) return; 11 12 // 模拟延迟 13 await new Promise(res => setTimeout(res, 1000)); 14 15 todos.push(newTodo); 16 console.log('Current Todos:', todos); 17 return { success: true, message: `'${newTodo}' added!` }; 18}

No configuration found for ID: ed42b26160a93c4d0a116ac619edaa27ae977be2fa7ee93f422539b963051b93

No configuration found for ID: 55f118e0e59e8293e72a99d20c53a5edfb6ba5fb1314f1f5d17f00a421a7a889

显示解决方案

以下是解决该练习的一种方式。

1. app/lib/actions.js 文件

此代码定义了一个 Server Action,用于从表单提交中读取反馈信息并在服务器上记录。

提交反馈的 Server Action

1// app/lib/actions.js 2 3'use server'; 4 5export async function submitFeedback(formData) { 6 const feedbackText = formData.get('feedback'); 7 console.log('New feedback received:', feedbackText); 8}

说明:

  • 第 3 行: 'use server' 指令确保从此文件导出的所有函数都是 Server Actions。

  • 第 5 行: 我们将 submitFeedback 定义为一个接受 formData 的 async 函数。

  • 第 6 行: 我们在 formData 上使用 .get() 方法,从名为 name="feedback" 的表单元素中提取值。

  • 第 7 行: 我们将提取的文本记录到服务器终端。

2. app/components/FeedbackForm.js 文件

此代码渲染一个客户端反馈表单,通过 Next.js 表单动作将用户输入提交到 Server Action。

反馈表单的客户端组件

1// app/components/FeedbackForm.js 2 3'use client'; 4 5import { submitFeedback } from '../lib/actions'; 6 7export default function FeedbackForm() { 8 return ( 9 <form action={submitFeedback} className="p-4 border rounded-lg"> 10 <h2 className="text-lg font-semibold mb-2">Leave Feedback</h2> 11 <textarea 12 name="feedback" 13 className="w-full p-2 border rounded" 14 placeholder="Tell us what you think..." 15 /> 16 <button type="submit" className="mt-2 bg-gray-700 text-white p-2 rounded"> 17 Submit 18 </button> 19 </form> 20 ); 21}

说明:

  • 第 5 行: 我们从 actions 文件中导入了 submitFeedback Server Action。

  • 第 9 行: 我们直接将导入的 submitFeedback 函数传递给 <form> 的 action 属性。Next.js 会自动处理提交过程,通过传入表单数据来调用此 Server Action。

  • 第 11–15 行: textarea 被赋予了 name="feedback" 属性。这是服务器端使用 formData.get('feedback') 来检索对应值的关键。

状态管理与客户端功能

使用 Server Actions 构建响应式表单