javascript - 在 React 中删除另一个对象内的一个对象
问题描述
首先,我知道 React 是 javascript,但这不是我能做到的原因。遵循“纯函数”的理念,我使用过滤器来删除东西。
问题是这样的:我有一个集合,每个集合都有一个标题和一个包含其他对象的数组,我想要做的是删除主对象数组中的一个特定对象。
例子:
// the state is like this
const collections = [
{
id: 3,
title: 'Machine Learning repos',
coll_type: 'r',
url: 'http://127.0.0.1:8000/api/collections/3/',
repos: [
{
id: 68,
name: 'tensorflow',
owner: 'tensorflow',
collection: 3
},
{
id: 76,
name: 'requests',
owner: 'kennethreitz',
collection: 3
}
]
}
]
当我单击要删除的按钮时,它会调用此函数,并传递集合的 id 和 repo:
const handleRepoDelete = (collectionId, repoId) => {
// get the collections state
const _newCollections = [...collections];
// get the collection by id
const collection = _newCollections.filter(
_collection => {
return _collection.id === collectionId
}
)[0]
// remove repo by id
collection.repos.filter(
repo => {
// here is not works
// is returning even when the ids are different
return repo.id !== repoId
}
)
// remove old collection with repo to delete
_newCollections.filter(
_collection => {
// here alse is not works
// is returning even when the ids are different, and the new and old collection
return _collection.id !== collection.id
}
)
// iterate in array with old collection deleted
// and add new collection with repo deleted
const newCollections = [..._newCollections, collection];
setCollections(newCollections);
}
问题是我不知道解决这个问题的最干净的方法,并且如您所见,单击的存储库没有在过滤方法中被删除。
解决方案
这是一个可能的解决方案。
const handleRepoDelete = (collectionId, repoId) => {
// we will map each item of the collections array
// will only change the collection with collectionId
// meaning, if not, we will return the original collection
const newCollections = collections.map(
(collection) => {
const {
id, repos
} = collection
// if the id doesn't match, just return it
if (id !== collectionId) {
return collection
}
// otherwise here we return a new object
// only changing repos prop of it
// using spread syntax, we filter repos
// at the end, we returned the collection
// with the changes we want
return {
...collection,
repos: repos.filter( ({ id }) => id !== repoId )
}
}
)
setCollections(newCollections);
}
推荐阅读
- python - 如何在 python 中使用类指针访问常量 - AUTH_USER_MODEL = 'django_restframework_2fa.User'
- html - 为 flexbox 单元格分配相同的宽度
- amazon-web-services - Amazon S3 映像名称在下载时显示不同的文件名或哈希码,而不是原始文件名
- javascript - 为什么有些脚本不能正确加载?
- dll - 使用 CMake 将所有 .lib 捆绑到一个 .dll 中?
- django - 如何在 AWS 上修复 Django“ModuleNotFoundError: No module named 'application'”?
- node.js - 是否可以使用 lambda 来触发雪花中的存储过程?
- reactjs - 有没有办法将 PageURL 参数传递给 Facebook PageView 事件?
- javascript - 如果我无法返回操作结果,如何返回上一个 location.href
- yii2 - Yii2 查询 where 和 or