如何解决在React useState挂钩中将对象推送到数组
我声明的反应状态如下
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])
但这对我没有帮助。
解决方法
您正在做
setselectedFiles(oldFiles => [...oldFiles,files])
这会将数组作为新元素添加到现有数组中 像这样的东西
let array = [1,2,3];
let array2 = [4,5,6];
let output= [...array,array2]
console.log(output) // [1,3,[4,6]]
// change the output which concat 2 arrays using spread
output= [...array,...array2];
console.log(output) // [1,4,6]
为您提供解决方案 替换
setselectedFiles(oldFiles => [...oldFiles,files])
作者
setselectedFiles(oldFiles => [...oldFiles,...files])
,
您可能在先前的阵列上有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"
]
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。