You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js服务端实现按钮点击触发API数据获取方法

在Next.js服务端组件实现按钮点击触发API数据获取

核心思路:用Server Actions实现服务端交互

Next.js 13+的Server Actions允许你在服务端组件中处理用户交互(比如按钮点击),无需将整个组件标记为客户端组件。

修改后的代码示例

  1. 定义Server Action
    创建一个带'use server'指令的异步函数,确保逻辑在服务端执行:
'use server';

import { get } from "@/services/ApiService";

export async function fetchPosts() {
  console.log("从服务端获取数据");
  const response = await get(`posts`);
  return response?.data;
}
  1. 修改About服务端组件
    移除页面初始化时的自动数据请求,改用表单提交触发Server Action,通过useActionState管理返回的数据:
import Button from "@/components/button/Button";
import { fetchPosts } from "./actions";
import { useActionState } from "react";

async function About() {
  // 初始化数据为null,绑定Server Action到状态
  const [posts, fetchPostsAction] = useActionState(fetchPosts, null);

  return ( 
    <div>
      Welcome to About test
      {/* 用form包裹按钮,点击时触发服务端动作 */}
      <form action={fetchPostsAction}>
        <Button type="submit" data="posts" />
      </form>
      {/* 渲染获取到的数据 */}
      {posts &&
        posts.map((item, index) => {
          return (
            <div key={index}>
              <div>{item.id}</div>
              <div>{item.title}</div>
            </div>
          );
        })}
    </div>
  );
}

export default About;

关键说明

  • 'use server'必须放在Server Action函数的最顶部,也可以单独封装到一个文件中,方便复用。
  • 用<form>包裹按钮并指定action为Server Action,点击按钮时会提交表单触发服务端API请求,整个About组件仍为服务端组件。
  • useActionState用于跟踪动作执行状态和返回结果,无需手动处理状态更新逻辑。

可选方案:无状态刷新

如果不需要实时管理状态,也可以让Server Action执行后触发页面重新验证,强制服务端重新渲染:

'use server';

import { get } from "@/services/ApiService";
import { revalidatePath } from 'next/cache';

export async function fetchPosts() {
  console.log("从服务端获取数据");
  const response = await get(`posts`);
  revalidatePath('/about'); // 重新验证当前页面路径
  return response?.data;
}

内容的提问来源于stack exchange,提问作者Nakeeb Raut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 20:46:20