next.js 如何将引用传递给服务器操作?

lnvxswe2  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(109)

我正在使用服务器操作来处理与表单一起提交的数据,我想将表单清除到操作中。
但操作不接收引用。
我的行动:

// actions/createVm.js
'use server'

export async function createVm(FormData) {
    const vm = await prisma.vm.create({
        data: {
            name: FormData.get("DisplayName"),
            ip: FormData.get("IpAddress"),
            group: {
                connect: { name: FormData.get("group") }
            }
        }
    })
    ref.current?.reset()
}

字符串
和形式:

// app/createVm/page.jsx
'use client'

import ButtonForm from "./button"
import { useRef } from "react"
import { createVm } from "@/actions/createVm"

export default function Form({ children }) {
  const ref = useRef(null)

    return(
        <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
            <form className="space-y-6" action={createVm} ref={ref}>
                { children }
                <ButtonForm />
            </form>
        </div>
    )
}


我如何使用引用?

ccgok5k5

ccgok5k51#

useRef是一个客户端概念。它简单地表示“引用DOM元素”。您不能将DOM元素传递给服务器(服务器上没有DOM)。

如何清除数据?

通过使用客户端操作:

// app/createVm/page.jsx
"use client";

import ButtonForm from "./button";
import { useRef } from "react";
import { createVm } from "@/actions/createVm";

export default function Form({ children }) {
    const ref = useRef(null);

    async function handleSubmit(formData) {
        // there is no directive here

        // run the server action
        await createVm(formData);

        ref.current.reset();
    }

    return (
        <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
            <form className="space-y-6" action={handleSubmit} ref={ref}>
                {children}
                <ButtonForm />
            </form>
        </div>
    );
}

个字符

j8ag8udp

j8ag8udp2#

如果您使用的是服务器操作,则可以使用useFormState访问表单状态

// your action
import { createVm } from "@/actions/createVm"

const ref = useRef<HTMLFormElement | null>(null);

const [formState, action] = useFormState(
    createVm.bind(null, { arg1, arg2 }),
    { errors: {} }
  );

// if useFormState value changes, your component will rerendered
// inside here using ref you can have control on form
useEffect(() => {
    if (formState.success) {
      ref.current?.reset();      
    }
  }, [formState]);

 <form action={ createVm} ref={ref}>
 ....
 </form>

字符串

相关问题