简体   繁体   中英

Update array of objects immutably and manage length redux

I am trying to save the search history in a react / redux app (using redux-actions) I am making in the reducer. I want to save the latest ten searches and have the latest at the beginning. I have an array of objects and I want to (immutably) add a new object at the beginning of the array and shift all the remaining results down one. I also don't want the array to grow larger than 10 elements. I am currently just overriding the initial element every time with this:

[setWorkPermit]: (state, action) => ({
  ...state,
  searchHistory: Object.assign([...state.searchHistory], { [0]: action.payload }),
}),

I was hoping there was a clean way to do this in ES6. Any takers?

I think array slices could do the trick here!

Just build a new array containing the new object at index zero, and then a slice of the previous 0-9 indices like this:

searchHistory: [action.payload, ...state.searchHistory.slice(0,9)],

Hopefully this helps!

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