Next.js 中的 Server Actions:处理表单的新方式
本文由原文机器翻译。
正在加载文章...
正在加载文章...
本文由原文机器翻译。
开发者们好!👋 准备好深入了解 Next.js 14 最酷的功能之一——Server Actions 吧。如果你一直在为 React 中的表单处理而苦恼,这可能会让你今天轻松不少!
Server Actions 是 Next.js 告别复杂 API 路由、迎接更简单直观的表单处理的方式。可以把它们看作你直连服务器的通道——无需中间人!🚀
// Your form component
export default function Form() {
async function handleSubmit(formData) {
'use server'
// Handle the form submission here
const name = formData.get('name')
await saveToDatabase(name)
}
return (
<form action={handleSubmit}>
<input name="name" type="text" />
<button type="submit">Submit</button>
</form>
)
}
很简洁,对吧?让我们用流程图拆解一下这里发生了什么:
'use server'
async function addTodo(formData) {
const todo = formData.get('todo')
try {
await db.todos.create({
data: {
content: todo,
completed: false
}
})
revalidatePath('/todos')
} catch (error) {
return { error: 'Failed to create todo' }
}
}
Server Actions 对 Next.js 开发者来说是颠覆性的。它们简化了我们的工作流,提高了安全性,并让我们的应用性能更好。在下一个项目中试试它们吧——未来的你会感谢现在的你!🎉
对 Server Actions 有疑问?在下方评论区留言吧!编码愉快!💻