更新项目数组中的单个值反应还原 [英] Update single value in item array | react redux

查看:136
本文介绍了更新项目数组中的单个值反应还原的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个待办事项列表,如果用户点击完成,则想要将数组中该项目的状态设置为完成。

I have a todo list and want to set the state of that item in the array to "complete" if the user clicks on "complete".

这是我的行动:

export function completeTodo(id) {
    return {
        type: "COMPLETE_TASK",
        completed: true,
        id
    }
}

这是我的减速器:

case "COMPLETE_TASK": {
             return {...state,
                todos: [{
                    completed: action.completed
                }]
             }
        }

我遇到的问题是新状态不再具有与所选项目上的待办事项关联的文本,并且ID不再存在。这是因为我覆盖了州并忽略了之前的属性吗?我的对象项onload如下所示:

The problem I'm having is the new state does no longer have the text associated of that todo item on the selected item and the ID is no longer there. Is this because I am overwriting the state and ignoring the previous properties? My object item onload looks like this:

Objecttodos: Array[1]
    0: Object
        completed: false
        id: 0
        text: "Initial todo"
    __proto__: Object
    length: 1
    __proto__: Array[0]
    __proto__: Object

如您所见,我想要做的就是将完成的值设置为true。

As you can see, all I want to do is set the completed value to true.

推荐答案

您需要转换todos数组以更新相应的项目。 Array.map是最简单的方法:

You need to transform your todos array to have the appropriate item updated. Array.map is the simplest way to do this:

case "COMPLETE_TASK":
    return {
        ...state,
        todos: state.todos.map(todo => todo.id === action.id ?
            // transform the one with a matching id
            { ...todo, completed: action.completed } : 
            // otherwise return original todo
            todo
        ) 
    };

有些库可以帮助您进行这种深度状态更新。您可以在此处找到此类库的列表: https://github.com/markerikson/redux-ecosystem-links/blob/master/immutable-data.md#immutable-update-utilities

There are libraries to help you with this kind of deep state update. You can find a list of such libraries here: https://github.com/markerikson/redux-ecosystem-links/blob/master/immutable-data.md#immutable-update-utilities

就个人而言,我使用ImmutableJS( https://facebook.github.io/immutable-js/ )通过其 updateIn setIn 方法(比普通对象和数组更有效)解决了这个问题对于具有大量键和数组的大型对象,对于小型对象则较慢。)

Personally, I use ImmutableJS (https://facebook.github.io/immutable-js/) which solves the issue with its updateIn and setIn methods (which are more efficient than normal objects and arrays for large objects with lots of keys and for arrays, but slower for small ones).

这篇关于更新项目数组中的单个值反应还原的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆