【问题标题】:Push Object to array in react useState hook在反应 useState 挂钩中将对象推送到数组
【发布时间】:2020-08-26 17:06:06
【问题描述】:

我声明反应状态如下

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

在下面的函数中使用它们

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

我正在尝试添加如下但不工作

selectedFiles.length === 0 ? setselectedFiles(files) : setselectedFiles(oldFiles => [...oldFiles,files])

但这对我没有帮助。

【问题讨论】:

标签: javascript reactjs use-state


【解决方案1】:

你在做 setselectedFiles(oldFiles => [...oldFiles,files])

这会将数组作为新元素添加到现有数组中 像这样的

let array = [1,2,3];
let array2 = [4,5,6];

let output= [...array,array2]
console.log(output) // [1,2,3,[4,5,6]]

// change the output which concat 2 arrays using spread 
output= [...array,...array2];

console.log(output) // [1,2,3,4,5,6]

所以对于您的解决方案 替换

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

通过

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

【讨论】:

  • 是的...使用[...new Set(YOUR_ARRAY)],或者如果您正在处理对象数组,请使用[...new Set(YOUR_ARRAY.map(JSON.stringify))].map(JSON.parse)...这不是最好的答案,尽管您会在数组中获得您的唯一值。
【解决方案2】:

你可能有setselectedFiles在前一个数组上具有相同的引用,这导致没有变化,所以将它克隆到一个新数组(我通过传播克隆)

function handleAcceptedFiles(files) {
  files.map((file) =>
    Object.assign(file, {
      preview: URL.createObjectURL(file),
      formattedSize: formatBytes(file.size),
    })
  )
  setselectedFiles([...files])
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2021-03-01
    • 1970-01-01
    • 2020-09-15
    相关资源
    最近更新 更多