Skip to content

ServerActions(少用,调试麻烦)

Server Actions 就是 Nextjs 框架内部代劳了提交数据部分的 HTTP 交互,为开发者省去了处理 HTTP 交互的模版代码,将更多的精力放在处理更需要创造力的地方。也让可读性更高。这种交互方式就类似于的 RPC 通讯。

简单来说 就是 服务器端发送请求.客户端看不到了(调试费劲)

基本用法

定义一个 Server Action 需要使用 React 的 "use server" 指令。按指令的定义位置分为两种用法:

    1. 将 "use server" 放到一个 async 函数的顶部表示该函数为 Server Action(函数级别)
    1. 将 "use server" 放到一个单独文件的顶部表示该文件导出的所有函数都是 Server Actions(模块级别)
  • 注意:

注意

Server Actions 可以在服务端组件使用,也可以在客户端组件使用。

当在服务端组件中使用的时候,两种级别都可以使用:

ts
// app/page.jsx
export default function Page() {
  // Server Action
  async function create() {
    'use server'

    // ...
  }

  return (
    // ...
  )
}

而在客户端组件中使用的时候,只支持模块级别。需要先创建一个文件(文件名无约定,很多开发者常命名为 "actions"),在顶部添加 "use server" 指令:

ts
"use server";

// app/actions.js
export async function create() {
  // ...
}

当需要使用的时候导入该文件即可

ts
import { create } from '@/app/actions'

export function Button() {
  return (
    // ...
  )
}

也可以将 Server Action 作为 props 传给客户端组件:

ts
<ClientComponent updateItem={updateItem} />
  • 使用
ts
"use client";

export default function ClientComponent({ updateItem }) {
  return <form action={updateItem}>{/* ... */}</form>;
}

举个例子

  • 新建app/form2/page.js代码如下
ts
import { findToDos, createToDo } from "./actions";

export default async function Page() {
  const todos = await findToDos();
  return (
    <>
      <form action={createToDo}>
        <input type="text" name="todo" />
        <button type="submit">Submit</button>
      </form>
      <ul>
        {todos.map((todo, i) => (
          <li key={i}>{todo}</li>
        ))}
      </ul>
    </>
  );
}
  • 新建app/form2/actions.js代码如下
ts
"use server";

const dynamic = "force-dynamic";

import { revalidatePath } from "next/cache";

const data = ["阅读", "写作", "冥想"];

export async function findToDos() {
  return data;
}

export async function createToDo(formData) {
  const todo = formData.get("todo");
  data.push(todo);
  revalidatePath("/form2");
  return data;
}