TypeError: AddTag is not a function React传addTag方法到子组件调用报错
错误触发原因
- React 函数组件仅接收1个props参数,父组件传递的所有属性都会挂载到这个参数对象上。你当前
Profile组件的参数写法const Profile = (user,{addTag}) => {}不符合规范:函数组件的第二个参数仅在配合forwardRef使用时接收ref,你把addTag放在第二个参数中无法正常获取,最终拿到的addTag值为undefined,调用时就会抛出「不是函数」的类型错误。 - 代码中还存在隐性问题:你用到的
cancelTag状态没有在Profile组件中定义,后续运行也会触发未定义报错。
修复方案
修改Profile组件的参数写法,常用有两种可选:
- 一次性解构所有props到参数中
const Profile = ({name, username, email, website, company, street, suite, city, zipcode, addTag}) => { // 补全cancelTag状态定义 const [cancelTag, setCancelTag] = useState(false) const [tagInput, setTagInput] = useState('') // 原有逻辑保持不变 }
- 先统一接收所有props到user变量,再单独解构
addTag
const Profile = (user) => { // 从props对象中解构addTag const { addTag } = user // 补全cancelTag状态定义 const [cancelTag, setCancelTag] = useState(false) const [tagInput, setTagInput] = useState('') // 原有逻辑保持不变 }
内容的提问来源于stack exchange,提问作者Orofin Adedamola
相关产品推荐
相关产品推荐

