gpt4 book ai didi

javascript - 如何从 React/Redux 中的数组中删除

转载 作者:行者123 更新时间:2023-11-30 11:31:35 25 4
gpt4 key购买 nike

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 函数中,我传递了状态(任务的完整数组)和该数组的索引号。我将如何使用索引删除该数组的元素。我觉得既然是 react ,我需要在其中使用过滤器吗?

最佳答案

你是对的,因为你使用的是 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
}

关于javascript - 如何从 React/Redux 中的数组中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46064460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com