首页 > 解决方案 > 无法在反应中重置复选框事件中已检查项目的值

问题描述

这是我第一次开发 React 应用程序。

我正在处理在反应表中获取勾选复选框的行 ID。我使用钩子将状态转移到另一个将显示值的组件。当复选框被勾选然后取消勾选时,未勾选的 id 仍然显示在状态中。我是否遗漏了一些可以刷新状态值的东西?

非常感谢。

export default function({ infinite }) {
const [checkedMap, setCheckedMap] = useState(new Map());
rows.forEach(row => newMap.set(row, false));

const handleCheckedChange = transaction_seq => {
    let modifiedMap = checkedMap;
    modifiedMap.set(transaction_seq, !checkedMap.get(transaction_seq));
    setCheckedMap(modifiedMap);
  };

const columns = [
    {
      Header: "Transaction(s)",
      className: "left",
      columns: [
        {
          id: "checkbox",
          accessor: "checkbox",
          Cell: ({ row }) => {
            return (
              <input
                type="checkbox"
                className="checkbox"
                checked={checkedMap.get(row.original.transaction_seq)}
                onChange={() =>
                  handleCheckedChange(row.original.transaction_seq)
                }
              />
            );
          },

          sortable: false,
          width: 45
        }

return (
    <React.Fragment>
      <Table
        {...{
          data,
          checkedMap,


编辑:我添加了 index.js

import React, { useState, useEffect, useRef } from "react";
//import makeData from "../makeData";
import { useTableState } from "react-table";
import Table from "../Table";
import axios from "axios";

// Simulate a server
const getServerData = async ({ filters, sortBy, pageSize, pageIndex }) => {
  await new Promise(resolve => setTimeout(resolve, 500));

  // Ideally, you would pass this info to the server, but we'll do it here for convenience
  const filtersArr = Object.entries(filters);

  // Get our base data
  const res = await axios.get(
    `url`
  );
  let rows = res.data;

  // Apply Filters
  if (filtersArr.length) {
    rows = rows.filter(row =>
      filtersArr.every(([key, value]) => row[key].includes(value))
    );
  }

  // Apply Sorting
  if (sortBy.length) {
    const [{ id, desc }] = sortBy;
    rows = [...rows].sort(
      (a, b) => (a[id] > b[id] ? 1 : a[id] === b[id] ? 0 : -1) * (desc ? -1 : 1)
    );
  }

  // Get page counts
  const pageCount = Math.ceil(rows.length / pageSize);
  const rowStart = pageSize * pageIndex;
  const rowEnd = rowStart + pageSize;

  // Get the current page
  rows = rows.slice(rowStart, rowEnd);

  return {
    rows,
    pageCount
  };
};

export default function({ infinite }) {
  const [checkedMap, setCheckedMap] = useState(new Map());
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const currentRequestRef = useRef();
  const [controlButton] = useState(0);

  let newMap = new Map();

  const fetchData = async () => {
    setLoading(true);

    // We can use a ref to disregard any outdated requests
    const id = Date.now();
    currentRequestRef.current = id;

    // Call our server for the data
    const { rows, pageCount } = await getServerData({
      filters,
      sortBy,
      pageSize,
      pageIndex
    });

    // If this is an outdated request, disregard the results
    if (currentRequestRef.current !== id) {
      return;
    }

    // Set the data and pageCount
    setData(rows);
    setState(old => ({
      ...old,
      pageCount
    }));

    rows.forEach(row => newMap.set(row, false));
    //setCheckedMap(newMap);

    setLoading(false);
  };

  const handleCheckedChange = transaction_seq => {
    let modifiedMap = checkedMap;
    const chh = modifiedMap.set(
      transaction_seq,
      !checkedMap.get(transaction_seq)
    );
    setCheckedMap(chh);
  };

  const columns = [
    {
      Header: "Transaction(s)",
      className: "left",
      columns: [
        {
          id: "checkbox",
          accessor: "checkbox",
          Cell: ({ row }) => {
            return (
              <input
                type="checkbox"
                className="checkbox"
                checked={checkedMap.get(row.original.transaction_seq)}
                onChange={() =>
                  handleCheckedChange(row.original.transaction_seq)
                }
              />
            );
          },

          sortable: false,
          width: 45
        },
        {
          Header: "Transaction Sequence",
          accessor: "transaction_seq",
          id: "transaction_seq",
          minWidth: 200,
          maxWidth: 300
        },
        {
          Header: "Record count",
          accessor: "record_count",
          width: 300
        },
        {
          Header: "User Id",
          accessor: "user_id",
          width: 300
        },
        {
          Header: "Updated At",
          accessor: "update_at",
          width: 400
        },
        {
          Header: "Duration",
          accessor: "duration",
          width: 400
        }
      ]
    }
  ];

  // Make a new controllable table state instance
  const state = useTableState({ pageCount: 0 });

  const [{ sortBy, filters, pageIndex, pageSize }, setState] = state;

  // When sorting, filters, pageSize, or pageIndex change, fetch new data
  useEffect(() => {
    fetchData();
  }, [sortBy, filters, pageIndex, pageSize]);

  return (
    <React.Fragment>
      <Table
        {...{
          data,
          checkedMap,
          controlButton,
          columns,
          infinite,
          state, // Pass the state to the table
          loading,
          manualSorting: true, // Manual sorting
          manualFilters: true, // Manual filters
          manualPagination: true, // Manual pagination
          disableMultiSort: true, // Disable multi-sort
          disableGrouping: true, // Disable grouping
          debug: true
        }}
      />
    </React.Fragment>
  );
}


标签: javascriptreactjs

解决方案


我认为这是 immutable.js?

当您set在 a 中输入值时Map,会将新Map返回给您:

所以这:

modifiedMap.set(transaction_seq, !checkedMap.get(transaction_seq));
setCheckedMap(modifiedMap);

应该:

const updatedMap = modifiedMap.set(transaction_seq, !checkedMap.get(transaction_seq));
setCheckedMap(updatedMap);

推荐阅读