React对象数组状态更新失效求助:输入框内容无法同步
问题分析与解决方案
核心问题
- 未传递索引参数:
handleChange函数需要接收index来定位要更新的数组元素,但输入框的onChange事件里没传这个参数,导致函数里的i === index永远不成立,无法更新对应 state。 - 未绑定输入框值:输入框没有绑定
value属性,属于非受控组件,就算 state 更新了,输入框也不会同步显示内容,看起来就像没更新一样。 - 变量名错误:
changeIloscSztuk函数里参数是event,但解构时用了e.target,会直接报错,这个也要一起修正。
修正后的代码
import React, { useState } from 'react'; import { Container, Table } from 'react-bootstrap'; const YourComponent = () => { // 初始state补充Wielkosc字段,和输入框对应 const [object, setObject] = useState([{ name: "", Description: "", Wielkosc: "", price: { A: "", B: "", C: "", } }]) // 修正变量名错误:参数改为e,对应解构的e.target const changeIloscSztuk = (e, index) => { const { name, value } = e.target; const tempProducts = object.map((el, i) => { if(i === index) { return { ...el, [name]: value }; } return el; }); setObject(tempProducts) } const handleChange = (e, index) => { const { name, value } = e.target; const tempProducts = object.map((el, i) => { if(i === index) { return { ...el, [name]: value }; } return el; }); setObject(tempProducts); }; // 补充添加新模块的逻辑 const setDodatkowe = (e) => { e.preventDefault(); setObject([...object, { name: "", Description: "", Wielkosc: "", price: { A: "", B: "", C: "" } }]); } return ( <> <Container style={{backgroundColor: "black", color: "white"}}> {object.map((item,i)=>{ return <span key={i}>{item.name} </span> })} </Container> <form onSubmit={setDodatkowe}> Dodaj nowy moduł <input type="submit" value="dodaj" /> </form> {object.length>0 && ( <form> <Table responsive striped bordered hover > <thead> <tr> <td>Nazwa usługi</td> <td>Opis</td> <td>Wielkość</td> <td>usun</td> </tr> </thead> <tbody> {object.map((props, index) => ( <tr key={index}> <td>Nazwa <input type="text" className="Nazwa" name="name" value={props.name} onChange={(e) => handleChange(e, index)} /></td> <td>Opis<input type="text" className="Description" name="Description" value={props.Description} onChange={(e) => handleChange(e, index)} /></td> <td>Wielkość <input type="text" className="Wielkosc" name="Wielkosc" value={props.Wielkosc} onChange={(e) => handleChange(e, index)} /></td> <td>{/* 可添加删除按钮:<button onClick={() => setObject(object.filter((_,i) => i!==index))}>Usuń</button> */}</td> </tr> ))} </tbody> </Table> </form> )} </> ) } export default YourComponent;
关键修改点
- 输入框的
onChange改为(e) => handleChange(e, index),传递当前元素索引 - 给每个输入框添加
value={props.对应字段},实现受控组件,同步state与输入框内容 - 初始state补充
Wielkosc字段,与输入框的name属性对应 - 修正
changeIloscSztuk里的变量名错误 - 补充
setDodatkowe函数实现,完成添加新模块的逻辑 - 优化表格结构,去掉多余嵌套的tr标签,避免渲染错误
内容的提问来源于stack exchange,提问作者user19358070
相关产品推荐
相关产品推荐

