如何从服务器操作 nextjs 渲染文本?

问题描述 投票:0回答:1

Next.js 新功能

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();


export default function Home() {

  const test = async (formData: FormData) => {
    "use server";

    const firstName = formData.get("firstName");
    const lastName = formData.get("lastName");
    const email = formData.get("email");

    const alreadyExists = await prisma.test.findFirst({
      where: {
        email: email as string
      }
    });

    if (alreadyExists) {
      return {
        message: "User already exists"
      };
    } else {
      await prisma.test.create({
        data: {
          firstName: firstName as string,
          lastName: lastName as string,
          email: email as string
        }
      });
    }
}

  return (
    <form action={test}>
      <input type="text" name="firstName" placeholder="firstName" className="bg-black"/>
      <input type="text" name="lastName" placeholder="lastName" className="bg-black"/>
      <input type="email" name="email" placeholder="email" className="bg-black"/>
      <input type="submit"/>
      <p>{message}</p>
    </form>
  );
}

这是我的代码,我想在 if 语句中渲染消息,但我无法让它工作,而且我不知道如何。

我厌倦了 useFormState,但我无法让它工作。

reactjs next.js server-side-rendering
1个回答
0
投票

您的

message
未定义。尝试使用 useState 或变量来捕获该结果。如果您想使用 useState,则必须将 Home 转换为客户端组件并提取测试函数,因为它是服务器操作。

// test.ts
"use server";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const test = async (formData: FormData) => {
  const firstName = formData.get("firstName");
  const lastName = formData.get("lastName");
  const email = formData.get("email");

  const alreadyExists = await prisma.test.findFirst({
    where: {
      email: email as string,
    },
  });

  if (alreadyExists) {
    return {
      message: "User already exists",
    };
  } else {
    await prisma.test.create({
      data: {
        firstName: firstName as string,
        lastName: lastName as string,
        email: email as string,
      },
    });
  }
};

// Home.tsx
"use client";
import { useState } from "react";
import { test } from "./test";

export default function Home() {
  const [msg, setMsg] = useState("");

  const submit = async (formData: FormData) => {
    const { message } = await test(formData);
    if (message) {
      setMsg(message);
    } else {
      // ...
    }
  };

  return (
    <form action={submit}>
      <input
        type="text"
        name="firstName"
        placeholder="firstName"
        className="bg-black"
      />
      <input
        type="text"
        name="lastName"
        placeholder="lastName"
        className="bg-black"
      />
      <input
        type="email"
        name="email"
        placeholder="email"
        className="bg-black"
      />
      <input type="submit" />
      <p>{msg}</p>
    </form>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.