[英]Update item in objects array based on object property
I have an array of objects with the below structure, how can I update the object's data ( file
) based on one of the object property ( name
)?我有一个具有以下结构的对象数组,如何根据 object 属性(
name
)之一更新对象的数据( file
)? for example how can I update the object named: test1
with a new file
object?例如,如何使用新
file
object 更新名为test1
的 object?
I have tried that but the correct object isn't being updated, a new object is being pushed to the array instead, what am I doing wrong?我已经尝试过了,但是正确的 object 没有更新,而是将新的 object 推送到阵列中,我做错了什么?
const [files, setFiles] = useState(fileArr)
const setFile = (name, data) => {
setFiles(files => ({...files, [name]: {...files[name], ...data}}))
}
fileArr
array: fileArr
数组:
const fileArr= [
{
name: 'test1',
status: 'Required',
file: {}
},
{
name: 'test2',
status: 'Required',
file: {}
},
{
name: 'test3',
status: 'Required',
file: {}
}
]
Assuming the following structure假设以下结构
const fileArr= [
{
name: 'test1',
status: 'Required',
file: {}
},
{
name: 'test2',
status: 'Required',
file: {}
},
{
name: 'test3',
status: 'Required',
file: {}
}
]
The correct way of updating an object based on name
to replace file
is根据
name
更新 object 以替换file
的正确方法是
const onChange = (name, data) =>{
setItems(items => items.map(item =>{
if(item.name === name)
//assuming you want to spread instead of overwrite 'file'
return {...item, file:{...item.file, ...data}}
return item
}))
}
Also you're initializing your state with fileList
which based on how you're trying to update is an object
, but you posted fileArr
as your data structure.此外,您正在使用
fileList
初始化您的 state ,基于您尝试更新的方式是object
,但您将fileArr
发布为您的数据结构。 So I'm assuming that you want to perform your operations in fileArr
instead of fileList
(which I don't know how it's look like)所以我假设你想在
fileArr
而不是fileList
中执行你的操作(我不知道它的样子)
I'm pretty sure it's because your not referencing the previous files
when you're using [name]
in your setFiles.我很确定这是因为您在 setFiles 中使用
[name]
时没有引用以前的files
。 I'd have thought the following should work.我原以为以下应该有效。
const setFile = (name, data) => {
setFiles(files => ({...files, files[name]: {...files[name], ...data}}))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.