简体   繁体   中英

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

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. 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.

From my opinion your code is absolutely normal for this particular task.

The current updateBookCopiesCount function is correct. 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.

See the Structuring Reducers - Immutable Update Patterns section of the Redux docs for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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