在React中删除另一个对象内的对象

时间:2019-06-12 22:00:36

标签: javascript reactjs

首先,我知道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和存储库:

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

问题是我不知道解决此问题的最干净方法,并且如您所见,单击的存储库未在filter方法中删除。

1 个答案:

答案 0 :(得分:1)

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

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