redux:使用不可变方法对数组中的对象进行性能修改 属性。优点和缺点

redux: Performance modifying property of an object in array using immutable approach. Pros and cons

根据我对函数式编程方式的基本理解以及当特定数组发生变化时我需要在 redux 中生成下一个状态的方式,我一直在尝试这种方法来通过待办事项列表中的索引修改待办事项:

const toggleSelectedTodo = (todos, selectedIndex) => {
    return todos.map((todo, index) => (
        { ...todo, completed: index === selectedIndex ? !todo.completed : todo.completed  }
    ))
}


export default function reducer(state = INITIAL_STATE, action) {
    switch (action.type) {
        ...
        case "TOGGLE_SELECTED":
            return {
                ...state,
                todos: toggleSelectedTodo(state.todos, action.index)
            }  
        ...

        default:
              return state
    }
}

所以,我的想法是我需要重新映射所有待办事项对象,以保持其值,目标项目除外。但是,我认为这不是高性能的,我担心大型阵列和最坏情况的性能。

您是否知道在数组中修改对象 属性 的更好策略或者这是执行此操作的正确方法?

您应该只修改具有选定索引的对象。无需对数组中的每个对象都使用扩展运算符。这可能是潜在的性能瓶颈。为避免您的 toggleSelectedTodo 函数应如下所示:

const toggleSelectedTodo = (todos, selectedIndex) => {
    return todos.map((todo, index) => {
        if(index === selectedIndex) {
          return { ...todo, completed: !todo.completed  }
        }
        return todo
    })
}

除此之外,除非您正在处理数千个项目,否则您不必担心性能。