NextJS actions 可以返回 JSX 组件,配合 useActionState,可以获取到 actions 操作返回的组件

定义 actions.jsx

"use server";
 
import { getList } from "./data";
import Posts from "./Posts";
 
export async function getPostPageAction(_, formData) {
  const page = formData.get("page") || 1;
  const posts = await getList(page);
  return <Posts posts={posts} />;
}

加载更多组件

"use client";
 
//@ts-ignore
import { useActionState, useState } from "react";
import { getPostPageAction } from "./actions";
 
const defaultComponent = null;
 
function LoadingPage({ page }) {
  const [component, formAction, isPending] = useActionState(
    getPostPageAction,
    defaultComponent,
  );
 
  return (
    component || (
      <form action={formAction}>
        <input type="text" name="page" value={page} />
        <button type="submit">{isPending ? "Pendding" : "Next Page"}</button>
      </form>
    )
  );
}
 
export default function List({ posts }) {
  const [page, setPage] = useState(2);
  return (
    <>
      {posts.map((v) => (
        <div key={v.page}>{v.page}</div>
      ))}
      <LoadingPage page={page} />
    </>
  );
}
 

文章地址: React 19 lets you write impossible components | Mux
React useActionState: useActionState – React
NextJS actions: Data Fetching: Server Actions and Mutations | Next.js