【问题标题】:Working with an LRU and redux store strategy使用 LRU 和 redux 存储策略
【发布时间】:2017-03-04 21:08:20
【问题描述】:

我想为 react-redux 应用程序实现 LRU,但是我不确定通过 reducer 将数据读取和写入存储的最佳策略是什么,以便我可以维护 LRU 结构。

目标是为最近的用户列表实施 LRU。实际上,只要应用程序单击特定联系人,他们就会被添加到最新的用户列表中。假设列表最多有 10 个用户,所以当它达到最大值时,我会有效地弹出列表中最旧的访问用户。

我可以为列表中的每个用户关联一个时间戳,但这意味着每次我从存储中读取状态时,我都必须排序并找到我觉得很慢的最旧的时间戳。

我是 React/Redux 的新手,所以请多多包涵。

任何建议表示赞赏!

谢谢, 德里克

【问题讨论】:

    标签: redux react-redux lru


    【解决方案1】:

    我只会有一个单独的减速器,它作用于“选择联系人”动作(可能还有另一个减速器也将作用于设置当前选定的用户)。它将保持数组并只是推到前面,如果最大值是到达者,则从末尾弹出。

    类似:

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

    然后像平常一样将它与其他减速器结合起来。

    【讨论】:

    • 谢谢,是的,这就是我最终做的事情
    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 2017-07-26
    • 2021-10-16
    • 2016-06-20
    • 1970-01-01
    • 2012-12-10
    相关资源
    最近更新 更多