错误:(0,react__WEBPACK_IMPORTED_MODULE_1__.useActionState)不是一个函数或其返回值不可迭代

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

我正在遵循

useActionState
在此处找到的示例。我正在使用 nextjs 和 typescript。

app/page.tsx

"use client";

import { useActionState } from "react";
import { createUser } from "../components/actions";

const initialState = {
  message: "",
};

export default function App() {
  const [state, formAction] = useActionState(createUser, initialState);

  return (
    <form action={formAction}>
      <label htmlFor="email">Email</label>
      <input type="text" id="email" name="email" required />
      {/* ... */}
      <p aria-live="polite" className="sr-only">
        {state?.message}
      </p>
      <button>Sign up</button>
    </form>
  );
}

../components/actions.ts

'use server'
 
export default async function createUser(prevState: any, formData: FormData) {
  return {
    message: 'Please enter a valid email',
  }
}

当我运行该示例时,我得到:

Error: (0 , react__WEBPACK_IMPORTED_MODULE_1__.useActionState) is not a function or its return value is not iterable

我的 package.json 看起来像:

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "db:migrate": "TS_NODE_COMPILER_OPTIONS='{ \"module\": \"commonjs\" }' knex migrate:latest",
    "db:migrate:undo": "TS_NODE_COMPILER_OPTIONS='{ \"module\": \"commonjs\" }' knex migrate:down",
    "db:migrate:make": "TS_NODE_COMPILER_OPTIONS='{ \"module\": \"commonjs\" }' knex migrate:make"
  },
  "dependencies": {
    "react": "canary",
    "react-dom": "canary",
    "react-scripts": "^5.0.0"
  },
  "main": "/index.js",
  "devDependencies": {}
}

我的

tsconfig.json

{
  "compilerOptions": {
    "target": "es2015",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}
javascript reactjs node.js typescript next.js
1个回答
0
投票

Next.js 添加了对 React 19 功能的支持,特别是

PR 65058
中的 useActionState
create-next-app
模板在 PR 65478 中添加了相同的支持。版本分别为 14.3.0-canary.45 和 14.3.0-canary.46。

因此,您可以通过运行

useActionState
或任何更高版本在 Next.js 中获得对
npx [email protected]
的支持。

© www.soinside.com 2019 - 2024. All rights reserved.