ReactJS动态表单提交数据库异常:仅插入一条0值数据求助
问题分析与解决方案
核心问题排查
你的代码存在几个关键问题,导致动态表单数据无法正确提交:
1. 状态更新的不可变处理不严谨
handleChange中仅复制了数组,但修改对象属性时直接操作原对象引用,React可能无法检测到状态变化。需要对数组内的对象也做浅拷贝:
let handleChange = (i, e) => { let newFormValues = [...formValues]; // 对目标索引的对象做浅拷贝,确保状态更新被React捕获 newFormValues[i] = {...newFormValues[i], [e.target.name]: e.target.value}; setFormValues(newFormValues); };
2. 冗余独立状态变量
你顶部定义的shared_no、no_of_rooms等独立state完全未使用,直接删除即可,避免混淆逻辑。
3. total_capacity字段未处理空值
该输入框未设置空值兜底,用户未输入时会传递undefined,后端接收后可能默认转为0:
<input type="number" style={{ width: '80px' }} name="total_capacity" value={element.total_capacity || ""} // 添加空值兜底 onChange={e => handleChange(index, e)}> </input>
4. 提交数据格式可能不匹配后端要求
你直接将formValues数组传给接口,但后端可能期望接收包裹数组的对象(比如{roomInfos: formValues})。先在提交前打印数据确认:
const saveRoomInfo = (e) =>{ e.preventDefault(); console.log("提交的数据:", formValues); // 控制台检查数据是否正确 // 若后端要求特定格式,调整为对应结构,例如: // const payload = {roomList: formValues}; RoomInfoService.createRoomInfo(formValues).then((response) => { console.log(response.data); navigate('/listroominfo'); }).catch(error =>{ console.log(error); }) }
5. 后端批量插入支持问题
如果后端仅支持单条记录插入,你需要遍历formValues逐个调用接口,或要求后端修改为支持批量接收数组数据。
关键代码修正片段
const RoomInfo = () => { // 删除冗余的独立state变量 let handleChange = (i, e) => { let newFormValues = [...formValues]; newFormValues[i] = {...newFormValues[i], [e.target.name]: e.target.value}; setFormValues(newFormValues); } const navigate = useNavigate(); let addFormFields = () => { setFormValues([...formValues, { shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: ""}]) }; let removeFormFields = (i) => { let newFormValues = [...formValues]; newFormValues.splice(i, 1); setFormValues(newFormValues) } const [formValues, setFormValues] = useState([{ shared_no: "", no_of_rooms: "", rent_per_month: "", total_capacity: "", vacancy: "" }]) const resetForm = () => setFormValues([{shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: ""}]); const Total_no_of_rooms_entered = () => { return formValues.reduce((total, element) => { return total + Number(element.no_of_rooms || 0); // 处理空值避免NaN }, 0); }; const saveRoomInfo = (e) =>{ e.preventDefault(); console.log("提交数据:", formValues); RoomInfoService.createRoomInfo(formValues).then((response) => { console.log(response.data); navigate('/listroominfo'); }).catch(error =>{ console.log(error); }) } return ( <> {/* 其余JSX保持不变,仅修正total_capacity输入框 */} <input type="number" style={{ width: '80px' }} name="total_capacity" value={element.total_capacity || ""} onChange={e => handleChange(index, e)}> </input> {/* 其余JSX结构 */} </> ) }
额外建议
- 提交前先通过控制台确认
formValues的所有字段值是否符合预期 - 核对后端接口的请求参数文档,确保前端传递的数据结构完全匹配
- 可为数字类型输入框设置默认值
0,避免空值引发的类型转换问题
内容的提问来源于stack exchange,提问作者Thunder
相关产品推荐
相关产品推荐

