【Next.js 项目实战系列】02-创建 Issue

news2024/10/21 13:40:24

原文链接

CSDN 的排版/样式可能有问题,去我的博客查看原文系列吧,觉得有用的话,给我的库点个star,关注一下吧 

上一篇【Next.js 项目实战系列】01-创建项目

创建 Issue

配置 MySQL 与 Prisma​

在数据库中可以找到相关内容,这里不再赘述

添加 model​

本节代码链接

# schema.prisma

model Issue {
  id Int @id @default(autoincrement())
  title String @db.VarChar(255)
  description String @db.Text
  status Status @default(OPEN)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt()
}

enum Status {
  OPEN
  IN_PROGRESS
  CLOSED
}

使用以下指令同步到数据库

npx prisma format
npx prisma migrate dev

编写 API​

本节代码链接

这里使用 zod 来验证表单,具体内容可参考使用 zod 验证表单

# /app/api/issues/route.ts

import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import prisma from "@/prisma/client";

const createIssueSchema = z.object({
  title: z.string().min(1).max(255),
  description: z.string().min(1),
});

export async function POST(request: NextRequest) {
  const body = await request.json();
  const validation = createIssueSchema.safeParse(body);
  if (!validation.success)
    return NextResponse.json(validation.error.errors, { status: 400 });

  const newIssue = await prisma.issue.create({
    data: { title: body.title, description: body.description },
  });

  return NextResponse.json(newIssue, { status: 201 });
}

Radix-UI​

本节代码链接

radix-ui 也是一个类 DaisyUI 的组件库,使用如下指令安装

npm install @radix-ui/themes

安装好后,进行如下初始配置,将主 layout 中的所有内容用 <Theme > 标签包起来

# /app/layout.tsx

  import type { Metadata } from "next";
+ import "@radix-ui/themes/styles.css";
  import { Inter } from "next/font/google";
+ import { Theme } from "@radix-ui/themes";
  import "./globals.css";
  import NavBar from "./NavBar";

  const inter = Inter({ subsets: ["latin"] });

  export const metadata: Metadata = {
    title: "Create Next App",
    description: "Generated by create next app",
  };

  export default function RootLayout({
    children,
  }: Readonly<{
    children: React.ReactNode;
  }>) {
    return (
      <html lang="en">
        <body className={inter.className}>
+         <Theme>
            <NavBar />
            <main>{children}</main>
+         </Theme>
        </body>
      </html>
    );
  }

创建新 Issue 页面​

本节代码链接

# /app/issues/new/page.tsx

"use client";
import { Button, TextArea, TextField } from "@radix-ui/themes";

const NewIssuePage = () => {
  return (
    <div className="max-w-xl space-y-3">
      <TextField.Root>
        <TextField.Input placeholder="Title" />
      </TextField.Root>
      <TextArea placeholder="Description" />
      <Button>Submit New</Button>
    </div>
  );
};
export default NewIssuePage;

显示效果如下 

New Issue Page

Radix-UI 定义 UI 样式​

本节代码链接

在 layout.tsx 中添加 <Themepanel >

# /app/layout.tsx

+ import { Theme, ThemePanel } from "@radix-ui/themes";
  ...
  return (
    <html lang="en">
      <body className={inter.className}>
        <Theme>
          <NavBar />
          <main className="p-5">{children}</main>
+           <ThemePanel />
        </Theme>
      </body>
    </html>
  );
  ...

效果如下

Theme Panel

调整好自己想要的样式之后点击 Copy Theme,将 copy 到的 <Theme > 标签替换掉原来的即可

  #  /app/layout.tsx
  ...
  return (
    <html lang="en">
      <body className={inter.className}>
        {/*添加到这里即可*/}
        <Theme appearance="light" accentColor="violet">
          <NavBar />
          <main className="p-5">{children}</main>
        </Theme>
      </body>
    </html>
  );
  ...

设置字体​

在 Radix-UI 中设置字体需要以下步骤,可以参考 radix-ui-font

首先在 layout.tsx 中修改

# /app/layout.tsx

  import { Theme } from "@radix-ui/themes";
  import "@radix-ui/themes/styles.css";
  import type { Metadata } from "next";
  import { Inter } from "next/font/google";
  import NavBar from "./NavBar";
  import "./globals.css";
- const inter = Inter({ subsets: ["latin"] });
+ const inter = Inter({
+   subsets: ['latin'],
+   variable: '--font-inter',
+ });
  export const metadata: Metadata = {
    title: "Create Next App",
    description: "Generated by create next app",
  };

  export default function RootLayout({
    children,
  }: Readonly<{
    children: React.ReactNode;
  }>) {
    return (
      <html lang="en">
-       <body className={inter.className}>
+       <body className={inter.variable}>
          <Theme appearance="light" accentColor="violet">
            <NavBar />
            <main className="p-5">{children}</main>
          </Theme>
        </body>
      </html>
    );
  }

然后添加 /app/theme-config.css 并添加以下内容

/app/theme-config.css

.radix-themes {
  --default-font-family: var(--font-inter);
}

最后在 layout.tsx 中 import 进来即可

···
import "./theme-config.css";
···

MarkDown Editor​

本节代码链接

react-simlemde-editor 是一款集成式 MarkDown 编辑器,使用如下命令安装

npm install --save react-simplemde-editor easymde

效果如下:

Simple MarkDown Editor

提交表单​

本节代码链接

我们使用 react-hook-form 和 axios 进行表单提交

npm i react-hook-form
npm i axios
# /app/issues/new/page.tsx

  "use client";
  import { Button, TextField } from "@radix-ui/themes";
  import { useRouter } from "next/navigation";
  // import
+ import axios from "axios";
+ import "easymde/dist/easymde.min.css";
+ import { Controller, useForm } from "react-hook-form";
+ import SimpleMDE from "react-simplemde-editor";

  // 使用 interface 表明 form 中有哪些内容
+ interface IssueForm {
+   title: string;
+   description: string;
+ }

  const NewIssuePage = () => {
    // 使用 React Hook Form
+   const { register, control, handleSubmit } = useForm<IssueForm>();
    // 使用 router 进行页面跳转
+   const router = useRouter();

    return (
      {/* 将最外层 div 换为 form */}
+     <form className="max-w-xl space-y-3"
+       onSubmit={handleSubmit(async (data) => {
          {/* 使用 axios 进行 post */}
+         await axios.post("/api/issues", data);
+         router.push("/issues");
+       })}>
        <TextField.Root>
          {/* 将该组件注册为 form 中的 title 字段 */}
+         <TextField.Input placeholder="Title" {...register("title")} />
        </TextField.Root>
        {/* 由于 simpleMDE 不能直接像上面的 Input 一样传入参数,我们这里使用 React Hook Form 中的 Controller */}
-       <SimpleMDE placeholder="Description" />
+       <Controller
+         name="description"
+         control={control}
+         render={({ field }) => (
+           <SimpleMDE placeholder="Description" {...field} />
+         )}
+       />
        <Button>Submit New</Button>
+     </form>
    );
  };
  export default NewIssuePage;

完整代码(非 git diff 版)

# /app/issues/new/page.tsx

"use client";
import { Button, TextField } from "@radix-ui/themes";
import axios from "axios";
import "easymde/dist/easymde.min.css";
import { useRouter } from "next/navigation";
import { Controller, useForm } from "react-hook-form";
import SimpleMDE from "react-simplemde-editor";

interface IssueForm {
  title: string;
  description: string;
}

const NewIssuePage = () => {
  const { register, control, handleSubmit } = useForm<IssueForm>();
  const router = useRouter();

  return (
    <form
      className="max-w-xl space-y-3"
      onSubmit={handleSubmit(async (data) => {
        await axios.post("/api/issues", data);
        router.push("/issues");
      })}
    >
      <TextField.Root>
        <TextField.Input placeholder="Title" {...register("title")} />
      </TextField.Root>
      <Controller
        name="description"
        control={control}
        render={({ field }) => (
          <SimpleMDE placeholder="Description" {...field} />
        )}
      />
      <Button>Submit New</Button>
    </form>
  );
};
export default NewIssuePage;

效果如下:

submit form

Handle Error​

本节代码链接

表单验证​

之前说到,我们使用 zod 进行表单验证,可以在使用 zod 时,自定义报错内容

# /app/api/issues/new/route.tsx

  ...
  const createIssueSchema = z.object({
    // 在定义时,可以加第二个参数,表示如果未满足该项时的报错
+   title: z.string().min(1, "Title is required!").max(255),
+   description: z.string().min(1, "Description is required!"),
  });

  export async function POST(request: NextRequest) {
    ...
    if (!validation.success)
    // 改为调用 validation.error.format()
-     return NextResponse.json(validation.error.errors, { status: 400 });
+     return NextResponse.json(validation.error.format(), { status: 400 });
    ...
  }

报错显示​

接下来实现一个这样的 Error Callout

Error Callout

在 /app/issues/new/page.tsx 中修改。把 axios 的相关内容放到一个 try-catch block 里

# /app/issues/new/page.tsx

  "use client";
  ...
  const NewIssuePage = () => {
    ...
    // 添加 useState 变量
+   const [error, setError] = useState("");

    return (
        ...
        {/*若报错则显示一个 CallOut*/}
+       {error && (
+         <Callout.Root color="red" className="mb-5">
+           <Callout.Text>{error}</Callout.Text>
+         </Callout.Root>
+       )}
        <form
          className="space-y-3"
          onSubmit={handleSubmit(async (data) => {
            // 报错时设置 error
+           try {
+             await axios.post("/api/issues", data);
+             router.push("/issues");
+           } catch (error) {
+             setError("An unexpected Error occured!");
+           }
          })}
        >
        ...
  };
  export default NewIssuePage;

用户端验证​

本节代码链接

Zod schema​

我们在用户端验证时,也需要用到刚刚 zod 中编辑的 schema,为此我们应该将其移动到一个单独的文件中。在 VS Code 中 可以方便的进行重构,将 createIssueSchema 移动到一个新文件中,并自动更新引用

首先右键想要重构的变量,点击 重构

Refactor 1

然后选择 move to a new file

Refactor 2

使用 Zod Schema 推断 interface​

将刚刚移出的 schema 移动到 /app 目录下,重命名为 validationSchema.ts

之前在 new page 中,我们定义了一个 interface,用于定义表单,但其实与我们在 zod 中定义的内容是重复的,如果我们之后还需要增删内容,需要在两边修改,较为麻烦。我们可以直接使用刚刚的 zod schema 来定义 interface ,如下所示

# /app/issues/new/page.tsx

+  import { createIssueSchema } from "@/app/validationSchema";
+  import { z } from "zod";
- interface IssueForm {
-   title: string;
-   description: string;
- }
+  type IssueForm = z.infer<typeof createIssueSchema>;

使用 hookform 集成 zod 验证表单​

安装 hookform/resolvers,用于将 React Hook Form 插件使用表单验证插件(比如 zod)

npm i @hookform/resolvers
# /app/issues/new/page.tsx
  
  "use client";
  ...
  // import
+ import { Button, Callout, Text, TextField } from "@radix-ui/themes";
+ import { zodResolver } from "@hookform/resolvers/zod";

  type IssueForm = z.infer<typeof createIssueSchema>;

  const NewIssuePage = () => {
    const {
      register,
      control,
      handleSubmit,
      // errors 则为验证结果
+     formState: { errors },
    } = useForm<IssueForm>({
      // 将 zodResoler 传入,以验证表单
+     resolver: zodResolver(createIssueSchema),
    });
    ...

    return (
      <div className="max-w-xl">
        ...
        <TextField.Root>
          <TextField.Input placeholder="Title" {...register("title")} />
        </TextField.Root>
        {/* 根据验证结果来显示提示,此处为 title 字段的信息 */}
+       {errors.title && (
+         <Text color="red" as="p">
+           {errors.title.message}
+         </Text>
+       )}
        <Controller
          name="description"
          control={control}
          render={({ field }) => (
            <SimpleMDE placeholder="Description" {...field} />
          )}
        />
        {/* 根据验证结果来显示提示,此处为 description 字段的信息 */}
+       {errors.description && (
+         <Text color="red" as="p">
+           {errors.description.message}
+         </Text>
+       )}
        ...
      </div>
    );
  };
  export default NewIssuePage;

最终效果如下:

Client Side Validation

将 ErrorMessage 封装​

# /app/components/ErrorMessage.tsx

import { Text } from "@radix-ui/themes";
import { PropsWithChildren } from "react";

const ErrorMessage = ({ children }: PropsWithChildren) => {
  if (!children) return null;
  return (
    <Text color="red" as="p">
      {children}
    </Text>
  );
};
export default ErrorMessage;

 然后我们可以在 new Page 中直接调用

# /app/issues/new/page.tsx

  "use client";
  ...
  // import
+ import ErrorMessage from "@/app/components/ErrorMessage";

    return (
      <div className="max-w-xl">
        ...
        {/* 根据验证结果来显示提示,此处为 title 字段的信息 */}
-       {errors.title && (
-         <Text color="red" as="p">
-           {errors.title.message}
-         </Text>
-       )}
+       <ErrorMessage>{errors.title?.message}</ErrorMessage>
        ...
-       {errors.description && (
-         <Text color="red" as="p">
-           {errors.description.message}
-         </Text>
-       )}
+        <ErrorMessage>{errors.description?.message}</ErrorMessage>
        ...
      </div>
    );
  };
  export default NewIssuePage;

Button 优化技巧​

本节代码链接

首先我们可以添加一个 Spinner 给 Button。其次,我们可以给 Button 添加一个 disabled 属性,使得其只能被点击一次,避免多次提交表单

Spinner 代码

# /app/issues/new/page.tsx

+ import Spinner from "@/app/components/Spinner";

  const NewIssuePage = () => {
+   const [isSubmitting, setSubmitting] = useState(false);

    return (
      <div className="max-w-xl">
        ...
        <form
          className="space-y-3"
          onSubmit={handleSubmit(async (data) => {
            try {
+             setSubmitting(true);
              await axios.post("/api/issues", data);
              router.push("/issues");
            } catch (error) {
+             setSubmitting(false);
              setError("An unexpected Error occured!");
            }
          })}
        >
          ...
+         <Button disabled={isSubmitting}>
+           Submit New Issue {isSubmitting && <Spinner />}
+         </Button>
        </form>
      </div>
    );
  };

最终版本​

本节代码链接

/app/issues/new/page.tsx

"use client";
import { Button, Callout, Text, TextField } from "@radix-ui/themes";
import axios from "axios";
import "easymde/dist/easymde.min.css";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import SimpleMDE from "react-simplemde-editor";
import { zodResolver } from "@hookform/resolvers/zod";
import { createIssueSchema } from "@/app/validationSchema";
import { z } from "zod";
import ErrorMessage from "@/app/components/ErrorMessage";

type IssueForm = z.infer<typeof createIssueSchema>;

const NewIssuePage = () => {
  const {
    register,
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<IssueForm>({
    resolver: zodResolver(createIssueSchema),
  });
  const router = useRouter();
  const [error, setError] = useState("");

  return (
    <div className="max-w-xl">
      {error && (
        <Callout.Root color="red" className="mb-5">
          <Callout.Text>{error}</Callout.Text>
        </Callout.Root>
      )}
      <form
        className="space-y-3"
        onSubmit={handleSubmit(async (data) => {
          try {
            await axios.post("/api/issues", data);
            router.push("/issues");
          } catch (error) {
            setError("An unexpected Error occured!");
          }
        })}
      >
        <TextField.Root>
          <TextField.Input placeholder="Title" {...register("title")} />
        </TextField.Root>
        <ErrorMessage>{errors.title?.message}</ErrorMessage>
        <Controller
          name="description"
          control={control}
          render={({ field }) => (
            <SimpleMDE placeholder="Description" {...field} />
          )}
        />
        <ErrorMessage>{errors.description?.message}</ErrorMessage>
        <Button>Submit New</Button>
      </form>
    </div>
  );
};
export default NewIssuePage;

CSDN 的排版/样式可能有问题,去我的博客查看原文系列吧,觉得有用的话,给我的库点个star,关注一下吧 

下一篇讲查看 Issue

下一篇【Next.js 项目实战系列】03-查看 Issue

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2220056.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

机器学习篇-day09-支持向量机SVM

一. 支持向量机介绍 支持向量机 介绍 SVM全称是Supported Vector Machine&#xff08;支持向量机&#xff09; 即寻找到一个超平面使样本分成两类&#xff0c;并且间隔最大。 是一种监督学习算法&#xff0c;主要用于分类&#xff0c;也可用于回归 与逻辑回归和决策树等其…

Android摄像头Camera2和Camera1的一些总结

Android 系统对摄像头的同时使用有限制&#xff0c;不能同时使用摄像头进行预览或者录制音视频。 例如&#xff1a;界面上有两个SurfaceView, 这两个SurfaceView不能同时预览或者录制音视频&#xff0c;只能有一个正常工作&#xff08;一个SurfaceView预览前置摄像头&#xff…

Linux 问题故障定位的技巧大全

1、背景 有时候会遇到一些疑难杂症,并且监控插件并不能一眼立马发现问题的根源。这时候就需要登录服务器进一步深入分析问题的根源。那么分析问题需要有一定的技术经验积累,并且有些问题涉及到的领域非常广,才能定位到问题。所以,分析问题和踩坑是非常锻炼一个人的成长和提…

Mybatis day 1020

ok了这周学习了mybatis框架&#xff0c;今天最后一天&#xff0c;加油各位&#xff01;&#xff01;&#xff01;(接上文) 八.MyBatis扩展 8.1 Mapper批量映射优化 需求 Mapper 配置文件很多时&#xff0c;在全局配置文件中一个一个注册太 麻烦&#xff0c;希望有一个办法…

MFC工控项目实例二十六创建数据库

承接专栏《MFC工控项目实例二十五多媒体定时计时器》 用选取的型号为文件名建立文件夹&#xff0c;再在下面用测试的当天的时间创建文件夹&#xff0c;在这个文件中用测试的时/分/秒为数据库名创建Adcess数据库。 1、在StdAfx.h文件最下面添加代码 #import "C:/Program F…

Ubuntu下安装Bochs2.7

文章目录 前言下载安装在Bochs实现最简单的操作系统创建软盘编写并编译汇编指令编写bochs配置文件将操作系统写入到软盘启动操作系统 前言 通过自带软件库sudo apt-get install bochs bochs-x安装的Bochs运行时不显示任何内容&#xff0c;这里选用源码安装方式。 下载安装 …

Atlas800昇腾服务器(型号:3000)—AIPP加速前处理(四)

服务器配置如下&#xff1a; CPU/NPU&#xff1a;鲲鹏 CPU&#xff08;ARM64&#xff09;A300I pro推理卡 系统&#xff1a;Kylin V10 SP1【下载链接】【安装链接】 驱动与固件版本版本&#xff1a; Ascend-hdk-310p-npu-driver_23.0.1_linux-aarch64.run【下载链接】 Ascend-…

CSS 居中那些事

一、父子元素高度确定 简单粗暴, 直接通过设置合适的 padding 或 margin 实现居中 <style>.p {padding: 20px 0;background: rgba(255, 0, 0, 0.1);}.c {width: 40px;height: 20px;background: blue;} </style> <div class"p"><div class"…

服务器模块测试

目录 测试逻辑 测试工具 测试 测试逻辑 我们可以使用一个简单的业务处理逻辑来进行测试。 最简单的&#xff0c;我们业务逻辑就直接返回一个固定的字符串 void Message(const PtrConnection&con,Buffer* inbuffer) //模拟用户新数据回调 {inbuffer->MoveReadOf…

Vite 前端开发的超级加速器 - 从入门到精通

大家好&#xff01;今天我们来聊聊前端开发中的一个革命性工具 - Vite。如果你觉得你的前端开发速度慢得像蜗牛爬&#xff0c;那么Vite就是为你量身打造的超级加速器&#xff01; 一、什么是Vite&#xff1f; Vite&#xff08;法语意为"快速"&#xff09;是一个现代化…

LDR6500芯片:引领USB-C拓展坞转接器新风

在当今这个数字化浪潮汹涌澎湃的时代&#xff0c;手机和电脑已然深深融入我们生活的每一个角落&#xff0c;成为了不可或缺的关键工具。然而&#xff0c;不得不承认的是&#xff0c;它们所配备的接口数量往往有限&#xff0c;难以充分满足我们日益多样化、丰富化的需求。正因如…

5G 现网信令参数学习(1) - MIB

MIB消息中的参数 systemFrameNumber 000101B, subCarrierSpacingCommon scs30or120, ssb-SubcarrierOffset 6, dmrs-TypeA-Position pos2, pdcch-ConfigSIB1 { controlResourceSetZero 10, searchSpaceZero 4 }, cellBarred notBarred, intraFreqReselection allowed, sp…

nginx解决非人类使用http打开的443,解决网安漏扫时误扫443端口带来的问题

一、问题描述 正常访问https的站点时&#xff0c;使用网址https://www.baidu.com&#xff0c;但会有一种错误的访问请求http://www.baidu.com:443&#xff0c;一般都是非人类所为&#xff0c;如漏洞扫描工具&#xff0c;那么请求以后带来的后果是个错误页面 400 Bad Request T…

Vue及项目结构介绍

今天滴学习目标&#xff01;&#xff01;&#xff01; 项目结构介绍1.Vue 项目文件结构2. 文件结构详解2.1 index.html2.2 src/main.js2.3 src/App.vue2.4 src/components/2.5 src/assets/2.6 package.json 3. 项目启动 首先我们先学习Vue项目结构&#xff0c;我们创建Vue项目时…

【专题】计算机网络之物理层

计算机网络体系结构&#xff1a; 1. 物理层的基本概念 物理层考虑的是怎样才能在连接各种计算机的传输媒体上传输数据比特流&#xff0c;而不是指具体的传输媒体。 作用&#xff1a;尽可能屏蔽掉不同传输媒体和通信手段的差异。 用于物理层的协议也常称为物理层规程 (procedu…

js.矩阵置零

链接&#xff1a;73. 矩阵置零 - 力扣&#xff08;LeetCode&#xff09; 题目&#xff1a; 给定一个 m x n 的矩阵&#xff0c;如果一个元素为 0 &#xff0c;则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。 示例 1&#xff1a; 输入&#xff1a;matrix [[1,1,1],…

如何使用Java语言调用API数据

在当今的数据驱动世界中&#xff0c;API&#xff08;应用程序编程接口&#xff09;成为了连接不同服务和数据源的桥梁。无论是社交媒体数据、金融市场信息还是地理位置服务&#xff0c;API都能提供一种便捷的方式来获取这些数据。Java&#xff0c;作为最受欢迎的编程语言之一&a…

无mac电脑在苹果开发者上传构建版本

我们登录苹果开发者网站的后台&#xff0c;进入app store后&#xff0c;发现上架的页面需要上传一个构建版本。 这个构建版本的意思就是我们的应用二进制文件&#xff0c;是上架最重要的文件。但是在苹果开发者后台是无法直接上传这个文件的&#xff0c;它提示我们可以使用xco…

VSCODE c++不能自动补全的问题

最近安装了vscode&#xff0c;配置了C/C扩展&#xff0c;也按照网上说的配置了头文件路径 我发现有部分头文件是没办法解析的&#xff0c;只要包含这些头文件中的一个或者多个&#xff0c;就没有代码高亮和代码自动补全了&#xff0c;确定路径配置是没问题的&#xff0c;因为鼠…

Caffeine Cache解析(一):接口设计与TinyLFU

Caffeine is a high performance Java caching library providing a near optimal hit rate. 自动加载value, 支持异步加载基于size的eviction&#xff1a;frequency and recency基于时间的过期策略&#xff1a;last access or last write异步更新valuekey支持weak referenceva…