英文:
Updating an item within an array and maintain its index
问题
我正在尝试使用传递给 response.payload
的新信息来更新我的状态。这是我的当前代码:
if (response.events.includes('databases.*.collections.*.documents.*.update')) {
setMemos(prevState => prevState.filter(memo => memo.$id !== response.payload.$id))
setMemos(prevState => [response.payload, ...prevState])
}
从技术上讲,它确实更新了信息,这正是我想要的,但它导致了项目失去了它的索引。我想简单地更新payload所指的特定“备忘录”并保持其索引。
这可能有点难以解释,如果你不明白我在说什么,只需告诉我,我会尽量进一步解释。
英文:
I'm trying to update my state with new information that is passed through response.payload
. This is my current code:
if(response.events.includes('databases.*.collections.*.documents.*.update')) {
setMemos(prevState => prevState.filter(memo => memo.$id !== response.payload.$id))
setMemos(prevState => [response.payload, ...prevState])
}
It does technically update the information which is what I wanted it to do however, it causes the item to lose its index. I want to simply update the specific "memo" that the payload is referring to and have it keep its index.
That was quite hard to explain so if you don't understand what I'm on about, just let me know and I'll try and explain further.
答案1
得分: 1
你可以尝试通过索引创建副本并进行更新,最后以以下方式返回:
if (response.events.includes('databases.*.collections.*.documents.*.update')) {
setMemos(prevState => {
// 创建前一个状态的副本
const updatedMemo = [...prevState];
// 找到与 $id 匹配的备忘录的索引
const memoIdx = updatedMemo.findIndex(memo => memo.$id === response.payload.$id);
// 如果找到了,在特定索引处进行更新
if (memoIdx !== -1) {
updatedMemo[memoIdx] = response.payload;
}
return updatedMemo;
});
}
请注意,代码部分未进行翻译,仅提供了代码注释的中文翻译。
英文:
You can try creating a copy and updating that by index and finally returning that like the following way:
if(response.events.includes('databases.*.collections.*.documents.*.update')) {
setMemos(prevState => {
//create a copy of the previus state
const updatedMemo = [...prevState];
//find the index of the memo that marches the $id
const memoIdx = updatedMemo.findIndex(memo => memo.$id === response.payload.$id);
//if found update in that specific index
if(memoIdx !== -1){
updatedMemo[memoIdx] = response.payload;
}
return updatedMemo;
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论