2017-09-05 68 views
1

如何从上午阵列去除反应,和/终极版

import dateDiff from 'date-diff'; 
 
import moment from 'moment'; 
 

 

 
const calcDate = (date) => { 
 
    let newDate = moment(new Date(date)).fromNow(); 
 
    console.log(newDate) 
 
    return newDate; 
 
};//end of calcDate 
 

 
const removeByIndex = (state=[], index) => { 
 
}; 
 

 

 

 
const addToListReducer = (state=[], action) => { 
 
    let reminders; 
 

 
    
 
    switch (action.type) { 
 
     case 'ADD_TO_LIST': 
 
      reminders = [...state, {task: action.task, dueDate:calcDate(action.dueDate)}] 
 
      console.log('this is the reminders in the reducer', reminders); 
 
      return reminders; 
 
     case "REMOVE_FROM_LIST": 
 
      console.log("Removing from the list", action.index) 
 
      reminders = removeByIndex(state, action.index) 
 
      return reminders; 
 
     default: 
 
      return state; 
 

 
    } //end of switch statement 
 
} 
 

 
export default addToListReducer;

在removeByIndex功能,我传递的状态(任务的全阵列)和数组的索引号。我将如何通过使用索引删除该数组的元素。我觉得既然是反应,我需要在其中使用过滤器?

+0

'arr.filter((ELEM,指数)=>收益指数==行动'' – mhodges

+0

'arr.slice(0,action.index).concat(arr.slice(action.index + 1))'也可以工作 – mhodges

回答

3

你说得对,因为你使用的是Redux,所以状态必须是不可变的。所以你不能直接编辑数组并返回它的同一个实例,而是你必须创建一个新的实例。

redux documentation,它解释了如何做到这一点的几种方法。

所以,你可以这样做:

function removeItem(array, index) { 
    return [ 
     ...array.slice(0, index), // first part of the array, 0 to index (excluded) 
     ...array.slice(index + 1) // the rest, after the index 
    ]; 
} 

或者简单(但可能不太高性能):

function removeItem(array, index) { 
    return array.filter((_, i) => i !== index); // all items except at index 
} 
+2

在这种情况下,我不会推荐使用“filter”来删除按指数。连接切片应该足够可读并且效率更高。 – souldzin

+0

'filter'可能更具可读性并且更短(特别是如果'removeItem'被转换为lambda),但是你是对的,如果性能是一个问题,那么应该使用第一个。我已经更新了我的答案,使其更清晰。 – Jonathan

+0

我猜可读性在旁观者眼中;)你已经赢得了我的+1 – souldzin