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

React开发动态输入框时报TypeError: inputList is not iterable错误如何解决?

错误根因

你定义的inputList是对象类型,但在handleChange和handleAddInput方法中,你错误地将其作为数组执行扩展操作[...inputList],普通对象本身不具备可迭代特性,因此直接抛出TypeError: inputList is not iterable报错。

你的核心操作目标是inputList内部的product_mix数组,而非修改外层inputList的整体结构,修正方法如下:

1. 状态定义修正(补全原代码缺失的闭合语法)

const [inputList, setInputList] = useState({
  product_docket: '',
  product_mix: [{ product: '', contains_percentage: '', quantity: '' }]
})

2. handleChange 方法修正

const handleChange = (e, index) => {
  const { name, value } = e.target
  // 拷贝外层inputList对象
  const newInputList = { ...inputList }
  // 修改product_mix对应下标的字段值
  newInputList.product_mix[index][name] = value
  setInputList(newInputList)
}

3. handleAddInput 方法修正

const handleAddInput = (e) => {
  e.preventDefault()
  setInputList({
    ...inputList,
    // 仅给product_mix数组追加新的空配置项
    product_mix: [
      ...inputList.product_mix,
      { product: '', contains_percentage: '', quantity: '' }
    ]
  })
}

4. 补充handleRemoveInput实现(原代码已调用该方法但未定义)

const handleRemoveInput = (e, index) => {
  e.preventDefault()
  const newInputList = { ...inputList }
  // 过滤掉要删除的下标对应项
  newInputList.product_mix = newInputList.product_mix.filter((_, i) => i !== index)
  setInputList(newInputList)
}

你原有的map渲染逻辑无需修改,调整以上代码后即可正常运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:24:03