简体   繁体   English

在反应 useState 钩子中将对象推送到数组时创建唯一的数组

[英]Create unique array while push Object to array in react useState hook

I am declaring react state as below我声明如下反应状态

const [selectedFiles, setselectedFiles] = useState([]);

Using them in function as below在功能中使用它们,如下所示

function handleAcceptedFiles(files) {
    files.map((file) =>
      Object.assign(file, {
        preview: URL.createObjectURL(file),
        formattedSize: file.size,
      })
    );
    selectedFiles.length === 0 ? setselectedFiles(files) : setselectedFiles(oldFiles => [...oldFiles,...files])
  }

At this point how can we add only new file and remove duplicate file此时我们如何只添加新文件并删除重复文件

setselectedFiles(oldFiles => [...oldFiles,...files])

You could create a lookup object with key-value pairs of filePreview-file and grab values from that您可以使用 filePreview-file 的键值对创建一个查找对象,并从中获取values

function handleAcceptedFiles(files) {
  const pendingFiles = files.map(file =>
    Object.assign(file, {
      preview: URL.createObjectURL(file),
      formattedSize: file.size
    })
  )

  const dedupFiles = Object.values(
    [...selectedFiles, ...pendingFiles].reduce((lookup, file) => {
      if (lookup[file.name] === undefined) {
        lookup[file.name] = file
      }
      return lookup
    }, {})
  )

  setselectedFiles(dedupFiles)
}

Maybe this is what you need?也许这就是你需要的?

function handleAcceptedFiles(files) {
  // Map over the current selection of files, generate required fields
  const newFiles = files.map(file => {
    return Object.assign(file, {
      preview: URL.createObjectURL(file),
      formattedSize: file.size,
    });
  });

  // Find non-duplicate entries in previously selected files
  const nonDupFiles = selectedFiles.filter(oldFile => {
    const index = newFiles.findIndex(newFile => newFile.preview === oldFile.preview);
    return index === -1;  // index -1 => file wasn't found => non duplicate
  });

  // Concat of new files and non-dup files is what we need in state
  setselectedFiles(newFiles.concat(nonDupFiles));
}

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

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