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

React组件调用addItemProp时出现TypeError报错求助

React组件报错:TypeError: undefined is not a function (near '...addItemProp...')

我是Node.js和JavaScript新手,一直遇到这个错误,即便经过多次搜索仍未找到解决方案,希望能得到帮助。

相关代码

import React, { useState } from "react";

export const ItemForm = ({ addItemProp }) => {
  const [Name, setName] = useState("");
  const [Price, setPrice] = useState("");
  const [description, setdescription] = useState("");
  const [Product, setProduct] = useState("");
  const [imagepath, setimagepath] = useState("");
  const [Category, setCategory] = useState("");

  const addItem = _=> { 
    addItemProp({
      id: (new Date).getTime(),
      Name,
      Price,
      description, 
      Product,
      Category,
      imagepath,
    });
    setName('')
    setPrice('');
    setdescription('');
    setProduct('');
    setCategory('');
    setimagepath('');
  } 

错误信息

TypeError: undefined is not a function (near '...addItemProp...')
报错位置:addItem函数,src/Components/AddProduct/addProduct.jsx第14行

13 |        const addItem = _=> { 
 14 |        addItemProp({
 15 |        id: (new Date).getTime(),
 16 |        Name,
 17 |        Price,

问题原因

这个错误的核心是:你在addItem函数里调用的addItemProp是undefined,说明使用<ItemForm>组件时,没有正确传入addItemProp这个回调属性,或者属性名拼写/大小写有误。

解决方法

  • 找到调用<ItemForm>的父组件,先定义一个处理新增商品的函数:
// 父组件示例代码
const handleAddItem = (newItem) => {
  // 这里写具体的添加逻辑,比如更新商品列表状态
  console.log('新增的商品数据:', newItem);
};
  • 在父组件中渲染<ItemForm>时,必须传入addItemProp属性:
<ItemForm addItemProp={handleAddItem} />
  • 检查属性名:确保父组件传入的属性名和子组件解构的addItemProp完全一致,不能出现拼写错误(比如写成addItem、AddItemProp)。

额外优化建议

  • 变量名遵循小驼峰规范:比如把Name改成name,Price改成price,这是JS/React通用编码习惯,能减少混淆。
  • 给addItemProp设置默认值,避免未传属性时直接报错:
export const ItemForm = ({ addItemProp = () => {} }) => {
  // ... 原有组件内容
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:50:26