You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js项目无法渲染handleSubmit获取的API返回数据求助

问题分析与修复方案

核心问题

  1. cart状态类型不匹配:初始设为数组[],但API返回的是对象结构,数组没有categoryTitle属性,导致渲染为空。
  2. 渲染路径错误:API返回的categoryTitle嵌套在products数组中,直接取cart.categoryTitle无法获取到值。
  3. 无效的Loading判断:sub、productResponse是未声明的变量,导致组件一直卡在Loading状态,无法渲染后续内容。
  4. 提交数据变量错误:提交时用了未定义的quantity,应该替换为counter。

具体修复步骤

1. 修正cart的初始状态

将cart的初始值改为空对象,并根据API返回结构定义类型:

const [cart, setCart] = useState<{ products?: Array<{ categoryTitle: string; sub: string; name: string[]; type: string; price: string; quantity: string }> }>({});

2. 调整渲染的取值路径

使用可选链操作符安全访问嵌套属性:

<p>{cart.products?.[0]?.categoryTitle}</p>

3. 移除无效的Loading判断

删除未声明变量的Loading检查,只保留categoryTitle的判断:

if (!categoryTitle) return <p>Loading</p>;

4. 修复提交数据的变量错误

将提交body中的quantity替换为counter:

body: JSON.stringify({
  products: [
    {
      categoryTitle,
      sub,
      name,
      type,
      price,
      quantity: counter, // 修正此处
    },
  ],
}),

修复后的完整代码示例

import { useEffect, useState } from "react";

const Lista = () => {
  const [categoryTitle, setCategoryTitle] = useState<any>();
  // 修正cart初始状态与类型
  const [cart, setCart] = useState<{ products?: Array<{ categoryTitle: string; sub: string; name: string[]; type: string; price: string; quantity: string }> }>({});

  interface Data {
    id: number;
    title: string;
  }

  useEffect(() => {
    handleCategoryData();
  }, []);

  async function handleCategoryData() {
    const response = await fetch("/api/category");
    const categoryTitle = await response.json();
    setCategoryTitle(categoryTitle);
  }

  const handleSubmit = async (event: any) => {
    event.preventDefault();
    
    const categoryTitle = event.target[0].value;
    const sub = event.target[1].value;
    const name = [event.target[2].value];
    const type = event.target[3].value == "Unidade" ? "unit" : "kg";
    const price = event.target[4].value;
    const counter = event.target[5].value;

    const res = await fetch("../api/list", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        products: [
          {
            categoryTitle,
            sub,
            name,
            type,
            price,
            quantity: counter, // 修正变量名
          },
        ],
      }),
    });
    const response = await res.json();
    console.log(response);
    setCart(response);
  };

  // 只保留有效的Loading判断
  if (!categoryTitle) return <p>Loading</p>;

  return (
    <>
      <section>
        <div className="listsContainer">
          <div className="cartContainer">
            <div className="listText">
              <p>Lista</p>
              {/* 使用可选链安全访问嵌套属性 */}
              <p>{cart.products?.[0]?.categoryTitle}</p>
              <p>0 categorias / 0 itens</p>
            </div>
          </div>
        </div>
      </section>
    </>
  );
};

export default Lista;

内容的提问来源于stack exchange,提问作者Piet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:41:01