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

标签 javascript reactjs

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/

相关文章:

javascript - 如何堆叠来自两个不同元素的按键事件和点击事件来触发相同的功能

javascript - ember 中的 helper 'andThen' 与传统的 'then' 有何不同

javascript - 如何传递父组件的状态以在子组件中使用?

reactjs - 带有 props.children 的 Typescript React 功能组件

javascript - 运算符 '>' 不能应用于 Angular 8 中的类型 'void' 和 'number'

javascript - 在 Azure 函数中检索设备孪生信息?

javascript - Angular 2 - 查看单个数据记录

javascript - Axios 到 Node (Express)GET 请求

javascript - 如何防止图像在 react native 中的 uri 重新加载时闪烁?

javascript - ReactJS - 通过 onclick 切换类