Next.js 开发入门之初识 Server Actions

844 阅读3分钟

如果你觉得这篇文章对你有所帮助,欢迎点赞加关注

Server Actions 是 Next.js 13.4 引入的一项新功能,这一功能为开发者提供了一种更直接、更简洁的方式在客户端和服务端之间交换数据,而无需通过传统的HTTP接口。Server Actions 是一种在服务器上运行的异步函数,并允许直接从 React 组件中调用。

Server Actions 通过使用 React 的 "use server" 指令来定义。我们可以将该指令放在异步函数的顶部,将该函数定义为 Server Action,或者将该指令放在单独文件的顶部,将该文件的所有导出定义为 Server Action。

需要强调的是,Server Action 的参数和返回值必须能被 React 序列化。

启用 Server Actions

在 Next.js 的 13.4 版本中,Server Actions 处于实验状态,要启用 Server Actions,你需要将next.config.js文件中的serverActions标志设置为true,来告诉 Next.js,你想在应用程序中使用此实验功能。具体方法如下:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    serverActions: true,
  },
};
module.exports = nextConfig;

编写 Server Action

"use server" 指令是 Server Actions 定义的重要组成部分,它可以确保使用该指令的函数只在服务器上执行。出于安全和性能方面的考虑,我们总是不希望敏感的服务器端逻辑在客户端暴露或运行。

下面介绍如何编写 Server Action:

export default function ServerComponent() {
  async function serverAction() {
    'use server';
    // 服务器端逻辑代码
  }
}

serverAction 是一个只在服务器上运行的函数,我们在函数正文中标记了 "use server" 指令。该函数的参数和返回值需要在服务器和客户端之间传输,因此它们必须是可序列化的。

与传统方法的比较

使用传统方式

如果不使用 Server Actions,处理服务器端逻辑的常用方法是在 Next.js 中使用 API。下面是一个示例,说明如何做到这一点:

// pages/api/createAccount.js
export default async function handler(req, res) {
  const { name, email, password } = req.body;
  // 保存到数据库或执行其他服务器端操作
  res.status(200).json({ status: 'success' });
}
// components/SignupPage.js
import { useState } from 'react';
export default function SignupPage() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const handleSubmit = async (event) =>
    event.preventDefault();
    const response = await fetch('/api/createAccount', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ name, email, password }),
    })
    if (response.ok) {
      const result = await response.json()
      console.log(result)
    } else {
      console.error('Error:', response.status)
    }
  }
  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={name} onChange={e => setName(e.target.value)} />
      <input type="email" value={email} onChange={e => setEmail(e.target.value)} />
      <input type="password" value={password} onChange={e => setPassword(e.target.value)} />
      <button type="submit">Create Account</button>
    </form>
  )
}

我们使用一个专用的API/api/createAccount,用于处理服务器端的账户创建逻辑。在客户端的SignupPage中,用户提交表单,表单数据将以POST请求方式发送至该API进行处理。

使用 Server Actions 方式

通过使用 Server Actions,可以简化这一过程:

// components/SignupPage.js
export default function SignupPage() {
  const createAccount = async (formData) => {
    "use server";
    const name = formData.get("name");
    const email = formData.get("email");
    const password = formData.get("password");
    // 保存到数据库或执行其他服务器端操作
  };
  return (
    <form action={createAccount} method="POST">
      <input type="text" name="name" />
      <input type="email" name="email" />
      <input type="password" name="password" />
      <button type="submit">Create Account</button>
    </form>
  );
}

createAccount函数是一个 Server Action,用于处理服务器端的账户创建逻辑。它直接从表单提交事件中调用,实现了服务器端和客户端代码的无缝对接。

结论

在 Next.js 中,Server Actions 是一个强大的功能,它通过将服务器端逻辑无缝集成到客户端组件中,极大地简化了 React 应用程序的开发过程。

值得注意的是,Server Actions 在初次接触时可能显得有些奇特,然而,经过深入了解,这种特性实际上有助于提高代码的简洁度和效率,极大增强了使用 Next.js 构建健壮、高效应用的能力。