在React useState挂钩中将对象推送到数组

时间:2020-08-26 17:06:06

标签: javascript reactjs use-state

我声明的反应状态如下

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])

但这对我没有帮助。

2 个答案:

答案 0 :(得分: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])

答案 1 :(得分:0)

您可能在先前的阵列上有from collections import defaultdict result = defaultdict(list) for values in my_list: for k, v in zip(values[::2], values[1::2]): result[k].append(v) print(result) 带有相同的引用,这不会导致任何更改,因此请将其克隆到一个新的阵列(我通过传播进行克隆)

{
    "full name ": [
        " Arthur Schopenhauer",
        " Aristotle"
    ],
    "date of birth ": [
        " Friday, February 22, 1788 (232 years ago)",
        " 384 BC (2403 years ago)"
    ],
    "place of birth ": [
        " Gdansk, Pomorskie, Poland",
        " Halkidiki, Macedonia Central, Greece"
    ],
    "date of death ": [
        " Friday, September 21, 1860 (age: 72 years) ",
        " 322 BC (age: 62 years) "
    ],
    "place of death ": [
        " Frankfurt, Hesse, Germany",
        " Evvoia, Greece Central, Greece"
    ]
}