简体   繁体   English

当更改一个键的值时,数据未在 object 数组中更新

[英]Data not getting updated in an array of object when changed value for one key

In an array of certain records in a table, which are comprised of Date and Text fields, any input is given or changed will set data accordingly.在由日期和文本字段组成的表中某些记录的数组中,给出或更改的任何输入都会相应地设置数据。 My concern is that when Date input is changed Text value is undefined although we have data for it on table, whereas when Text input is changed Date value is undefined.我担心的是,当日期输入更改时,文本值未定义,尽管我们在表中有它的数据,而当文本输入更改时,日期值未定义。 My intention is that I need to show all data associated to it with that respective id.我的意图是我需要显示与其相关的所有数据以及相应的 id。 Please go through the code below:请通过以下代码拨打go:

const handleChange = (data) => {
    const { id: newId, textVal: franchise, dateVal: dateData } = data;
    setDataNew((prevInfo) => {
      const newList = [...prevInfo];
      const index = newList.findIndex((datum) => datum.newId === newId);
      if (index !== -1) {
        if (newId !== undefined) {
          newList[index].newId = newId;
        }
        if (franchise !== undefined) {
          newList[index].franchise = franchise;
        }
        if (dateData !== undefined) {
          newList[index].dateData = dateData;
        }
      } else {
        newList.push({ newId, franchise, dateData });
      }
      return [...newList];
    });
  };

As you can see from above code, we have data shown only on onChange.从上面的代码可以看出,我们的数据只在 onChange 上显示。 How can we show both object data when any either of data is changed.当任何一个数据发生变化时,我们如何显示两个 object 数据。

在此处输入图像描述

Please refer to the image as well, when any data changed for date text is undefined and vice-versa for other.请同时参考图像,当日期文本更改的任何数据未定义时,反之亦然。

Please also refer to codesandbox link --> https://codesandbox.io/s/dazzling-frost-htyzhm?file=/src/Table.js另请参考codesandbox链接--> https://codesandbox.io/s/dazzling-frost-htyzhm?file=/src/Table.js

In the codesandbox I see that dataNew it's initialized as an empty array, so when you call setDataNew() it creates a new object that has only the properties you're setting in the update function. You need to initialize dataNew with the data that you are using on the table.在 codesandbox 中,我看到dataNew被初始化为空数组,因此当您调用setDataNew()时,它会创建一个新的 object,它仅具有您在更新 function 中设置的属性。您需要使用您设置的数据初始化dataNew正在桌子上使用。

I have looked through your code an i noticed that you are missing to pass those values in your callbacks.我查看了您的代码,发现您没有在回调中传递这些值。

So extend you callbacks in your Grid.js like this:因此,像这样在 Grid.js 中扩展回调:

onChange={(e) => {
    textCallback({
        textVal: e.target.value,
        id: rowData[0].id,
        dateVal: rowData[4]
    });
}}

and

onChange={(e) => {
    dateCallback({
        textVal: e.target.value,
        id: rowData[0].id,
        dateVal: rowData[3]
    });
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM