使用$ splice(来自immutability-helper)比过滤器从React中的数组中删除项目有什么好处?

问题描述 投票:6回答:1

我正在使用immutability-helper对状态数据进行CRUD操作,并想知道我是否应该总是使用$splice来删除数据,或者是否可以使用filter(因为它不具有破坏性)?

例如,假设我有一个对象数组:

todos = [
 {id: 1, body: "eat"},
 {id: 2, body: "drink"},
 {id: 3, body: "sleep"},
 {id: 4, body: "run"}
]

给定一个项目ID,我可以通过两种方式删除它:

一个。找到它的index并使用$splice

index = todos.findIndex((t) => { return(t.id === id) });
newtodos = update(todos, { $splice: [[index, 1]] })

要么

湾使用filter

newtodos = todos.filter((t) => { return(t.id === id) });

filter更简洁但我不确定与在这种情况下使用$splice相比它是否有任何缺点。

javascript reactjs immutability
1个回答
1
投票

使用immutability-helper

处理nested collection很方便:

const collection = [1, 2, { todos: [...todos] }];
const newCollection = update(collection, {
  2: {
    todos: {
      $apply: todos => todos.filter(t => t.id !== id)
    }
  }
});

并且,它为您提供了collectioncollection[2]的新副本:

console.log(newCollection === collection, newCollection[2] === collection[2]);
//false false

因此,如果您使用react-reduxconnect状态到组件,如果您希望在状态更改时重新呈现组件,则必须返回新的状态副本。

用旧方法做这个运算符:

const todoList = collection[2].todos;
const idx = todoList.findIndex(t => t.id === id);
const newTodoList = update(todoList, { $splice: [[index, 1]] });
const newCollectionTwo = [...collection];
newCollectionTwo[2] = {
  todos: newTodoList
};

并使用控制台查看:

console.log(collection, newCollectionTwo, collection === newCollectionTwo, collection[2] === newCollectionTwo[2]); 

对于简单的数据结构和运算符,我认为它与filter相同。

抱歉我的英语不好,这是我的意见。

© www.soinside.com 2019 - 2024. All rights reserved.