简体   繁体   English

不变地更新对象数组并管理长度减少

[英]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. 我试图将搜索历史保存在我在reducer中制作的react / redux应用程序中(使用redux-actions)。 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. 我也不希望数组增长到大于10个元素。 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. 我希望在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: 只需构建一个新数组,其中包含索引为零的新对象,然后像这样的先前的0-9索引切片:

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

Hopefully this helps! 希望这会有所帮助!

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

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