复选框已更改,未在反应中更新

时间:2019-05-24 05:58:23

标签: javascript reactjs

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

在react中检索checkedMap useState挂钩时遇到问题,无论何时选中然后取消选中复选框,该挂钩都不会更新其状态。无论下一个实例是否已取消选中,该状态似乎都会保存选中的条目。

我访问了by的值:Array.from(checkedMap.keys()));

场景1 复选框A-勾选 复选框B-选中

checkedMap =复选框A和B的ID

场景2 复选框A-勾选 复选框B-未选中

checkedMap =复选框A和B的静态ID //应该仅是复选框A的ID

非常感谢您的帮助。

import React, { useState, useEffect, useRef } from "react";

// 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 here`
  );
  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();

  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;
    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)
                }
              />
            );
          },

const state = useTableState({ pageCount: 0 });

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

  const paginationButtons = (
    <React.Fragment>
      <Button onClick={() => reprocessConfirmation()}>Reprocess</Button>
      <Button onClick={() => reprocessConfirmation()}>View Details</Button>
    </React.Fragment>
  );

  function reprocessConfirmation() {
    let confirmation = window.confirm(
      "Do you want to reprocess transaction sequence " +
        Array.from(checkedMap.keys())
    );

    if (confirmation === true) console.log(Array.from(checkedMap.keys()));
    else console.log("CANCEL");
  }

  function updateConfirmation() {
    let confirmation = window.confirm("Do you want to update transaction");
    if (confirmation === true) console.log("OK");
    else console.log("CANCEL");
  }

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

  return (
    <React.Fragment>
      <MyTable
        {...{
          data,
          checkedMap,
          paginationButtons,
          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>
  );
}

1 个答案:

答案 0 :(得分:0)

由于您只是切换了check和uncheck的值,因此当取消选中该复选框时,该键仍然存在。您必须删除该键或在地图中寻找一个真值,而不是仅仅检查该键是否为存在与否。

第二个解决方案的代码段

function reprocessConfirmation() {
    const keys = [];
    checkedMap.forEach((value, key) => {
        if(value) keys.push[key]
    })
    let confirmation = window.confirm(
      "Do you want to reprocess transaction sequence " +
        keys
    );

    if (confirmation === true) console.log(keys);
    else console.log("CANCEL");
  }