首页 > 解决方案 > 在 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);
}

问题是我不知道解决这个问题的最干净的方法,并且如您所见,单击的存储库没有在过滤方法中被删除。

标签: javascriptreactjs

解决方案


这是一个可能的解决方案。

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);
}

推荐阅读