简体   繁体   中英

What's the advantage of using $splice (from immutability-helper) over filter to remove an item from an array in React?

I'm using immutability-helper for doing CRUD operations on state data and want to know if I should always use $splice for removing data or is it ok to use filter (since it's not destructive)?

For example, let's say I have an array of objects:

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

Given an item id, I can remove it in two ways:

a. find its index and use $splice :

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

OR

b. use filter :

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

filter is more concise but I'm not sure if it has any disadvantages compared to using $splice in this case.

use immutability-helper :

it's convenient to process nested collection :

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

and, it give you a new copy for collection and collection[2] :

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

So, if you use react-redux , connect state to component, if you want your component re-render when the state changed, you must return a new copy of state.

Do this operator with old way:

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

and take a look with console:

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

for simple data structure and operator, i think it's equal with filter .

Sorry for my English is not good, and this is my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM