在`use client`客户端页面中使用
返回主页
我们可以在纯粹的客户端use client页面(page.tsx)中使用serverAction方法。但是一定要注意:
  1. serverAction必须封装到独立的模块中,比如action.ts
  2. action.ts中必须标记use server
  3. action.ts中所有函数必须是·异步函数·

可以看到,我们轻松的集成了后端调用能力,但是却没有任何API接口

  • action.ts文件内容如下:
"use server";
export async function getUsers() {
  await new Promise((resolve) =>
    setTimeout(resolve, 1000 + Math.random() * 1000)
  );
  return [
    { id: 1, name: `John_${Math.random()}` },
    { id: 2, name: `Mary_${Math.random()}` },
    { id: 3, name: `Tom_${Math.random()}` },
  ];
}
  • page.tsx`文件内容如下:
"use client";
import { useState } from "react";
import { getUsers } from "./action";
import Code from "./code.mdx";
export default function Page() {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<{ name: string }[]>([]);
  return (
    <div>
      <div> 预览:</div>
      <button
        disabled={loading}
        className='btn'
        onClick={async () => {
          setLoading(true);
          try {
            setData(await getUsers());
          } finally {
            setLoading(false);
          }
        }}
      >
        {loading ? "Loading..." : "Call Server Action"}
      </button>
      <div>
        datas:
        {data.map((item, index) => (
          <div key={index}>{item.name}</div>
        ))}
      </div>
    </div>
  );
}
预览:
datas: