企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## useFormState app/action.tsx ``` 'use server' import { redirect } from 'next/navigation' // 定义状态类型 type State = { message?: string; success?: boolean; } | null; // 修改 action 函数的类型定义 export async function createUser(prevState: State, formData: FormData): Promise<State> { try { const res = await fetch('https://...') const json = await res.json() if (!res.ok) { return { message: '请输入有效的邮箱地址', success: false } } return { message: '创建成功', success: true } } catch (error) { return { message: '发生错误,请稍后重试', success: false } } } ``` app/page.tsx ``` 'use client' import { useFormState } from 'react-dom' import { createUser } from '@/app/actions' export default function SignupForm() { // 初始化 formState const [state, formAction] = useFormState(createUser, null) return ( <form action={formAction}> {state?.message && ( <p className={state.success ? 'text-green-500' : 'text-red-500'}> {state.message} </p> )} <input type="email" name="email" /> <button type="submit">注册</button> </form> ) } ``` > 表单的信息会提交给acton 出来,如果有错误的话,会再 state 中接收 ## Error Page - 错误会会抛向最近一层 ### 入门 报错 ``` import { Demo } from "."; export default function BlogPage() { throw new Error('Not implemented') return <div>Blog a <Demo /> </div> } ``` app/dashboard/error.tsx ``` 'use client' // Error boundaries must be Client Components import { useEffect } from 'react' export default function Error({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { useEffect(() => { // Log the error to an error reporting service console.error(error) }, [error]) return ( <div> <h2>Something went wrong!</h2> <button onClick={ // Attempt to recover by trying to re-render the segment () => reset() } > Try again </button> </div> ) } ``` ### global-error ``` 'use client' // Error boundaries must be Client Components export default function GlobalError({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { return ( // global-error must include html and body tags <html> <body> <h2>Something went wrong!</h2> <button onClick={() => reset()}>Try again</button> </body> </html> ) } ```