this.setState 删除过滤器 - ReactJS

this.setState deletes filter - ReactJS

好的伙计们,我这里有一个问题。 几天以来我一直在解决这个问题,所以如果有人能给我提示我该如何解决,我会很高兴。 (或者有人可以提出解决方案)。 所以我设法通过 material-table 库创建了自己的 table。但就我而言,我需要将 docIDdocNR 作为每个复选框的值。这就是为什么我使用 material-ui - <Checkbox/> 中的一个单独组件。 总之,我发现我的问题来自我的 handleCheckBox 函数。特别是来自我的更新状态函数 this.setState 。我的问题是因为我的 setState 函数是 Asynchronous 吗?或者你会说我做错了什么。

视觉示例

我的方法

handleCheckboxClick = (clickedItem) => {

        let newDocList = { ...this.state.docList };
        if (clickedItem.checked) {
            newDocList[clickedItem.documentId] = clickedItem.documentNumber;
        } else {
            delete newDocList[clickedItem.documentId];
        }

        let toSee = Object.keys(newDocList).length > 0 ? true : false;

        this.setState({
                docList: newDocList,
                visible: toSee
            }, () => {
                console.log()
            });

        const updatedArray = this.state.items.map((item) => {
            item.checked = item.documentId === clickedItem.documentId ? !item.checked : item.checked;
            return item;
        });

        this.setState({

            items: updatedArray,
        });
    };

P.S.

我尝试了一个只有控制台初始化的空函数,它运行得非常棒。

这里的问题是,在选中该框后,您的 table 会重新呈现,这会使其重新创建列数组。该数组用于存储过滤数据。

您需要做的是将列数据存储在呈现函数之外的某个位置。看一个简单的例子 useState(或考虑 redux/mobx):


const BasicFilteringWithState = () => {
  const [columnsData] = useState([
    { title: "Name", field: "name" },
    { title: "Surname", field: "surname" },
    { title: "Birth Year", field: "birthYear", type: "numeric" },
    {
      title: "Birth Place",
      field: "birthCity",
      lookup: { 34: "İstanbul", 63: "Şanlıurfa" }
    }
  ]);

  return (
    <MaterialTable
      title="Basic Filtering Preview"
      columns={columnsData}
      data={[
        { name: "Mehmet", surname: "Baran", birthYear: 1987, birthCity: 63 },
        {
          name: "Zerya Betül",
          surname: "Baran",
          birthYear: 2017,
          birthCity: 34
        }
      ]}
      options={{
        filtering: true
      }}
    />
  );
};

看看这个沙箱:https://codesandbox.io/s/laughing-einstein-1ig9m

我保留了示例并添加了带有 useState 的示例。您可以同时过滤 table,然后单击底部的测试按钮。你会看到区别的。

在相关说明中,不要忘记检查 table 为什么会因为复选框而重新呈现。这可能表明您的组件未优化(记忆)...