从无法正常工作的数组中删除对象 - React-dropzone

Deleting an object from an array not working properly - React-dropzone

我正在使用 react-dropzone 上传一些文件并使用 react-bootstrap-table-next 显示上传的文件元数据。我尝试从文件列表中删除一个对象,如果我从列表中随机删除文件,它就无法正常工作。请指教

这是我的codesandbox link: link

这是我的代码:

import "./styles.css";
import { Box } from "reflexbox/styled-components";
import { isEmpty, reject } from "lodash";
import BootstrapTable from "react-bootstrap-table-next";
import paginationFactory from "react-bootstrap-table2-paginator";
import React, { useState, useCallback } from "react";
import { useDropzone } from "react-dropzone";
import { IconNames } from "@blueprintjs/icons";

import { NonIdealState, Text, Button, Colors, Icon } from "@blueprintjs/core";

const getFormattedFileSize = (bytes, decimals = 2) => {
  if (bytes === 0) return "0 Bytes";

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
};

function Basic(props) {
  const [myFiles, setMyFiles] = useState([]);

  const onDrop = useCallback(
    (acceptedFiles) => {
      const files = [...myFiles, ...acceptedFiles];
      const filesWithId = files.map((item, index) => {
        return {
          id: index + 1,
          lastModified: item.lastModified,
          lastModifiedDate: item.lastModifiedDate,
          name: item.name,
          size: item.size,
          type: item.type,
          webkitRelativePath: item.webkitRelativePath
        };
      });
      setMyFiles(filesWithId);
    },
    [myFiles]
  );

  const { getRootProps, getInputProps } = useDropzone({
    accept: "image/jpeg",
    onDrop
  });

  const removeFile = (file) => {
    console.log("file", file);
    const newFiles = [...myFiles];
    setMyFiles(reject(newFiles, { id: file.id }));
  };

  const fileSizeFormatter = (cell) => {
    return <span>{getFormattedFileSize(cell)}</span>;
  };

  const fileNameFormatter = (cell) => {
    return <Text ellipsize>{cell}</Text>;
  };

  const fileDeleteFormatter = (cell, row) => {
    return (
      <Button
        minimal
        icon={<Icon icon={IconNames.TRASH} color={Colors.RED1} />}
        onClick={() => removeFile(row)}
      />
    );
  };

  const uploadedFilesColumns = [
    {
      dataField: "name",
      text: "File Name",
      formatter: fileNameFormatter,
      sort: true
    },
    {
      dataField: "size",
      text: "File Size",
      formatter: fileSizeFormatter,
      sort: true
    },
    {
      dataField: "delete",
      text: "Delete",
      formatter: fileDeleteFormatter
    }
  ];
  console.log(myFiles);

  return (
    <section className="container">
      <div {...getRootProps({ className: "dropzone" })}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <Box className="border p-3">
        <Box
          {...getRootProps({ className: "dropzone" })}
          style={{ cursor: "pointer" }}
        >
          <input {...getInputProps()} accept=".jpg" />
          <NonIdealState
            icon={"import"}
            title="Drag 'n' drop some files here, or click to select files"
          />
        </Box>
        {!isEmpty(myFiles) && (
          <Box className="pt-1">
            <BootstrapTable
              bootstrap4
              keyField="id"
              data={myFiles}
              columns={uploadedFilesColumns}
              pagination={paginationFactory({ showTotal: true })}
            />
          </Box>
        )}
      </Box>
    </section>
  );
}

export default Basic;

图片 Link:Images link

截图:

当您更改时,问题似乎已解决:

const removeFile = (file) => {
    console.log("file", file);
    const newFiles = [...myFiles];
    setMyFiles(reject(newFiles, { id: file.id }));
  };

直接在setMyFiles()中调用旧状态值:

 const removeFile = (file) => {
    console.log("file", file);

    setMyFiles((oldStateVal) => reject(oldStateVal, { id: file.id }));
  };