onChange反应无法正常工作

时间:2020-11-04 15:45:45

标签: javascript reactjs typescript functional-programming

鉴于表的这种数据类型是对象的数组:

[
    {
        "1": {
            "1": "Item s ",
            "2": "Manufacturer ",
            "3": "Mir s ",
            "4": "Decoription ",
            "5": "Contents ",
            "6": "UOM ",
            "7": "Total Ship Total Qty ",
            "8": "% of Purohasec ",
            "9": "Involoe Count ",
            "10": "K Brand "
        },
        "2": {
            "1": "fdsa ",
            "2": "fdsa fdsa ",
            "3": "16-fsd ",
            "4": "fds fdsa TW fsda",
            "5": "100 ",
            "6": "B) ",
            "7": "6 ",
            "8": "0.17 ",
            "9": "3 ",
            "10": ""
        },
      }, 
    ....
]

我具有显示要编辑的“行”的组件。我正在显示由json数据支持的表单和表格(上面),以为我使用表格并将其设置为状态,视图重新呈现并给了我更改。上面的数据类型将采用上述格式,但是标题,表数和字段都可能在运行之间发生变化。另外,我对数据类型没有太多控制。作为属性传递的表是在下面的cellChange中看到的tableCopy。

const [tablesCopy, setTablesCopy] = useState<any>({});

...

const InvRow = ({ rowTarget, clearEditRow, table, cellChange }: { rowTarget: string, clearEditRow: Function, table: any; cellChange: Function; }) => {
  const tt = tableTarget(rowTarget);

  const editRow = [];

  if (tt) {
    const labels = table[tt.table][1];
    const values = table[tt.table][tt.row];

    const keys = Object.keys(labels);
    for (let key of keys) {
      const name = `t_${tt.table}_r_${tt.row}_c_${key}`;
      editRow.push(<tr>
        <td>{labels[key]}</td>
        <td><Input type="text" value={values[key]} name={name} id={name} onChange={(e) => cellChange(e)} /></td>
      </tr>);
    }
  }

  return (
    <>
      <Table>{editRow}</Table>
      <div>
        <Button onClick={(e) => clearEditRow(e)} color="primary" size="lg">Close</Button>
      </div>
    </>

  );
};

我在cellChange方法上的操作如下,并且使用预期的输入正确触发了该操作:

  const cellChange = (e: React.BaseSyntheticEvent) => {

    const tt = tableTarget(e.target.id);
    console.log("cellChange -> tt", tt);
    tablesCopy[tt.table][tt.row][tt.cell] = e.target.value;
    setTablesCopy(tablesCopy);

  };

但是,在显示中,旧值并没有被onChange事件替换,尽管在控制台中,我可以看到该事件被正确的值触发。

是否有任何建议更好地实现此onChange,还是我应该采取不同的策略?

编辑:添加我的useEffect初始化:

  useEffect(() => {
    const fetchData = async () => {
      const path = "/tables.json";
      const response = await fetch(path);
      const tables: any = await response.json();
      setTablesOrig(tables);
      setTablesCopy({ ...tables });
      const tableKeys = Object.keys(tablesCopy);
      setNumOfTables(tableKeys.length);

    };
    fetchData();
  }, []);

1 个答案:

答案 0 :(得分:1)

您应该克隆数据对象。如果您在表中仅使用from shapely.geometry import Point import geopandas as gpd from geopandas import GeoDataFrame import pandas as pd df = pd.read_csv("File.csv", skiprows=0, low_memory=False, encoding='ANSI') geometry = [Point(xy) for xy in zip(df['longitude'], df['latitude'])] gdf = GeoDataFrame(df, geometry=geometry) #this is a simple map that goes with geopandas world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) gdf.plot(ax=world.plot(figsize=(10, 6)), color='red', markersize=1.5) stringnumber,则应该可以正常工作:

bool

在此处查看深度对象克隆的其他选项:What is the most efficient way to deep clone an object in JavaScript?

UPD: 如注释中所述,您可以使用传播语法进行复制,但是,这样做const cellChange = (e: React.BaseSyntheticEvent) => { const tt = tableTarget(e.target.id); console.log("cellChange -> tt", tt); var tables = JSON.parse(JSON.stringify(tablesCopy)); // <- clone tables[tt.table][tt.row][tt.cell] = e.target.value; setTablesCopy(tables); }; 还不够,但是您还应该克隆要更改的表,行和单元格。 正确的方法如下:

{...tablesCopy}