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
相关产品推荐
相关产品推荐

