简体   繁体   English

在Redux Reducer中,如何更新数组对象内的1个属性

[英]In redux reducer how to update 1 property inside array object

I have a reducer, that first gets a list of books array objects without the book copies count property, and than for each book it get the number of copies 我有一个化简器,它首先获取没有书本计数属性的书本数组对象列表,然后为每本书获取书本数

const bookList= (state = [], action) => {
    switch (action.type) {
        case 'BOOKS_REQUEST_SUCCEEDED':
            return Object.assign({}, state, action.payload);
        case 'BOOKS_COUNT_REQUEST_SUCCEEDED':
           return updateBookCopiesCount(state, action);
        default:
            return state
    }
}

const updateBookCopiesCount = (state, action) => {
   const newState = state.map((book) => { // updating only the book copies count
        if (book.Id === action.payload.Id) {
           return { ...book,
               copiesCount: action.payload.copiesCount 
           };
        }
        return book;
   });
   return newState;
}

my question is, what is the right redux approach: should I copy each time the entire array with all the objects for each copiesCount update, or is it ok to copy only the object that was modified with the new property 我的问题是,正确的redux方法是什么:我应该每次复制整个数组以及每个copysCount更新的所有对象时,还是应该只复制使用new属性修改过的对象?

Thanks in advance 提前致谢

Redux only requires that you have to return new value instance if there was any changes in data, ie it enforces immutability. Redux仅要求如果数据有任何更改,则必须返回新的值实例,即,它强制不变性。 And it doesn't enforce the particular form of your reducer. 而且它不强制执行减速器的特定形式。 So, your question effectively isn't about redux approach, but about general javascript task how to perform data transformation in immutable way. 因此,您的问题实际上不是关于redux方法,而是关于如何以不变的方式执行数据转换的一般javascript任务。

From my opinion your code is absolutely normal for this particular task. 我认为您的代码对于此特定任务绝对是正常的。

The current updateBookCopiesCount function is correct. 当前的updateBookCopiesCount函数正确。 You need to copy each level of nesting that needs to be updated, but only what needs to be updated. 您需要复制需要更新的嵌套的每个级别,但复制需要更新的嵌套。 So, you need to copy state (which is being done via state.map() , and you need to copy just the one object inside of the array that needs to be updated. All other objects should be returned as-is. 因此,您需要复制state (这是通过state.map() ,并且需要复制数组中需要更新的一个对象。所有其他对象应按原样返回。

See the Structuring Reducers - Immutable Update Patterns section of the Redux docs for more info. 有关更多信息,请参见Redux文档的“ 构造化约化器-不可变的更新模式”部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM