通过示例快速学习 useActionState (Nextjs

通过示例快速学习 useactionstate (nextjs

使用表单时,useactionstate 挂钩简化了捕获表单值并将其作为 formdata 传递到服务器操作的过程。

useactionstate 还通过使用服务器操作返回的值自动更新状态变量来管理状态。这对于渲染输入字段验证错误特别有帮助,如下面使用 zod 的示例所示。

form.tsx:

"use client";import { useactionstate } from "react";import { signup } from "../actions";export default function signup() {  const [state, action] = useactionstate(signup, {});  return (          
{state.errors?.username && (

{state.errors.username}

)}
{state.errors?.password && (

{state.errors.password}

)}
);}

登录后复制

actions.ts:

"use server";import { z } from "zod";const SignUpSchema = z.object({  username: z.string(),  password: z    .string()    .min(8, { message: "Be at least 8 characters long" })    .regex(/[a-zA-Z]/, { message: "Contain at least one letter." })    .regex(/[0-9]/, { message: "Contain at least one number." })    .regex(/[^a-zA-Z0-9]/, {      message: "Contain at least one special character.",    })    .trim(),});export type SignUpActionState = {  username?: string;  password?: string;  errors?: {    username?: string[];    password?: string[];  };};export async function signUp(  _prevState: SignUpActionState,  form: FormData): Promise {  const username = form.get("username") as string;  const password = form.get("password") as string;  const validatedFields = SignUpSchema.safeParse({    username,    password,  });  if (!validatedFields.success) {    return {      username,      password,      errors: validatedFields.error.flatten().fieldErrors,    };  }  // process validated form inputs here  return { username, password };}

登录后复制

useactionstate 还返回一个 ispending 属性(示例),指示服务器操作的 promise 是否仍在解析。

参考 ispending 暂时禁用表单元素,例如提交按钮,以防止用户在正在进行的操作完成之前快速连续多次单击它。

useactionstate 与 useformaction 和 useformstatus

如果您熟悉 useformaction 和 useformstatus,您会发现 useactionstate 非常相似。

本质上,它结合了两个钩子的功能,并被重命名以反映服务器操作不仅仅适用于表单(您还可以将 useactionstate 与按钮和其他元素一起使用。)

请记住,useformstatus 从 next.js 15 开始已被弃用,因此您应该继续导入 useactionstate。

以上就是通过示例快速学习 useActionState (Nextjs的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2650920.html

(0)
上一篇 2025年3月7日 08:41:20
下一篇 2025年2月28日 06:52:14

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论