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

如何传递useState的第二个参数作为Props?解决调用未定义对象错误

解决"Cannot invoke an object which is possibly 'undefined'"错误

错误原因拆解

  1. Props类型定义完全错误:你把setcollection定义成了any[]数组类型,但它实际是useState返回的状态更新函数,而且还加了可选符号?,TypeScript认为它可能是undefined,所以调用时报错。
  2. 状态更新逻辑错误:父组件的collection是数组类型,但你直接把字符串input传给setcollection,会导致数组被替换成字符串,类型不匹配。
  3. 未阻止表单默认行为:点击submit按钮会触发表单默认提交,页面会刷新,状态会丢失。

修正后的代码

父组件(显式指定数组类型,类型更明确)

const App: React.FC = () => {
  const [collection, setCollection] = useState<string[]>([])
  return (
    <div>
      <Input setcollection={setCollection} />
    </div>
  )
}

子组件(核心修改)

// 修正Props类型:定义为状态更新函数,去掉可选符号确保必传
interface InputProps {
  setcollection: React.Dispatch<React.SetStateAction<string[]>>
}

const Input: React.FC<InputProps> = ({ setcollection }) => {
  const [input, setInput] = useState('')
  
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    setInput(value)
  }

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    // 阻止表单默认提交,避免页面刷新
    e.preventDefault()
    // 函数式更新数组,基于最新状态添加新元素
    setcollection(prev => [...prev, input])
    // 提交后清空输入框
    setInput('')
  }

  return (
    <div className="container">
      <form onSubmit={handleSubmit}>
        <input onChange={handleChange} placeholder="Input Data" value={input} />
        <button type="submit">Submit</button>
      </form>
    </div>
  )
}

关键修改点说明

  • 修正Props类型:用React.Dispatch<React.SetStateAction<string[]>>准确定义状态更新函数的类型,同时去掉?,确保setcollection一定存在,消除undefined的可能。
  • 优化表单提交:把触发逻辑移到form的onSubmit事件上,调用e.preventDefault()阻止页面刷新;使用函数式更新数组,保证操作基于最新的数组状态。
  • 受控输入框:给input加上value={input},让输入框成为受控组件,状态同步更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:12:25