debugging 错误:backingFormData.forEach不是函数,nextjs13

x9ybnkn6  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(80)

我尝试使用Nextjs 13中的新功能“服务器操作”,但我得到“错误:当使用服务器操作提交表单时,backingFormData.forEach不是函数

import { useState} from 'react'

export interface Product {
  id?: number;
  product: string;
  price: string;
}

export default async function Home() {
  const res = await fetch(
    "https://64bda1242320b36433c7c958.mockapi.io/product",
    {
      cache: "no-cache",
    }
  );

  const addProductToDatabase = async (e: FormData) => {
  "use server"
  //   const product = e.get("product")?.toString();
  //   const price = e.get("price")?.toString();
  //   if (!product || !price) return;
  //   const newProduct: Product = {
  //     product,
  //     price
  //   } 
  //   await fetch('https://64bda1242320b36433c7c958.mockapi.io/product', {
  //     method: 'POST',
  //     body: JSON.stringify(newProduct),
  //     headers: {
  //       'Content-Type':'application/json'
  //     }
  //   })
  };
  const products: Product[] = await res.json();

  return (
    <main>
      <h1 className="text-3xl font-bold text-center">
        Testing product server function
      </h1>

      <form
        action={addProductToDatabase}
        className="flex flex-col gap-5 max-w-xl mx-auto p-5"
      >
        <input
          name="product"
          type="text"
          className="border border-gray-300 p-2 rounded-md"
          placeholder="Enter product name"
        />
        <input
          name="price"
          type="text"
          className="border border-gray-300 p-2 rounded-md"
          placeholder="Enter product price"
        />
        <button className="border bg-blue-500 text-white p-2 rounded-md">
          Add product
        </button>
      </form>

      <h2 className="font-bold p-5">list of products</h2>
      <div className="flex flex-wrap gap-5">
        {products.map((product) => (
          <div key={product.id} className="p-5 shadow">
            <p>{product.product}</p>
            <p>R$: {product.price}</p>
          </div>
        ))}
      </div>
    </main>
  );
}

字符串
代码和https://www.youtube.com/watch?v=W6V91VeghjI&t=1040s&ab_channel=SonnySangha教程中的一样,我也试着在github上运行其他人的一些项目,但都得到了同样的错误,我怀疑servers action在nextjs13中停止工作了?

u59ebvdq

u59ebvdq1#

我在Node版本18上遇到了同样的错误。更新到版本20,它工作得很好。

相关问题