如何从上午阵列去除反应,和/终极版
问题描述:
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功能,我传递的状态(任务的全阵列)和数组的索引号。我将如何通过使用索引删除该数组的元素。我觉得既然是反应,我需要在其中使用过滤器?
答
你说得对,因为你使用的是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
}
'arr.filter((ELEM,指数)=>收益指数==行动'' – mhodges
'arr.slice(0,action.index).concat(arr.slice(action.index + 1))'也可以工作 – mhodges