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

React对象数组状态更新失效求助:输入框内容无法同步

问题分析与解决方案

核心问题

  1. 未传递索引参数:handleChange 函数需要接收 index 来定位要更新的数组元素,但输入框的 onChange 事件里没传这个参数,导致函数里的 i === index 永远不成立,无法更新对应 state。
  2. 未绑定输入框值:输入框没有绑定 value 属性,属于非受控组件,就算 state 更新了,输入框也不会同步显示内容,看起来就像没更新一样。
  3. 变量名错误: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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:48:21