我想为 react-redux 应用程序实现 LRU,但是我不确定通过 reducer 将数据读取和写入存储的最佳策略是什么,以便我可以维护 LRU 结构。
目标是为最近的用户列表实现 LRU。实际上,只要应用程序单击特定联系人,他们就会被添加到最新的用户列表中。假设列表最多有 10 个用户,所以当它达到最大值时,我会有效地弹出列表中最老的访问用户。
我可以为列表中的每个用户关联一个时间戳,但这意味着每次我从存储中读取状态时,我都必须排序并找到我认为最慢的最旧时间戳。
我是 React/Redux 的新手,所以请多多包涵。
任何建议表示赞赏!
谢谢, 德里克
最佳答案
我只会有一个单独的 reducer 来作用于“选择联系人”操作(可能还有另一个 reducer 也将作用于设置当前选定的用户)。它将维护数组并只是推到前面,如果最大值是 reachers,则从末尾弹出。
类似于:
const initialState = []
export const lruReducer = (state = initialState, action) => {
switch(action.type) {
case 'SELECT_CONTACT':
// copy the previous array (I'm assuming ES6 syntax here, but you could use Object.assign or ImmutableJS or something if preferred)
// this is important to keep the state immutable
let newState = [...state]
// add the new contact (this is where you would do any de-duping logic
newState.unshift(action.user)
// keep removing items until constraint is met
while (newState.length > 10) {
newState.pop()
}
// return new array
return newState
default:
return state
}
}
然后像往常一样将它与您的其他 reducer 结合起来。
关于redux - 使用 LRU 和 redux 存储策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42601434/