2017-09-05 66 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