redux - 使用 LRU 和 redux 存储策略

标签 redux react-redux lru

我想为 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/

相关文章:

reactjs - 如何在不同的 URL 路由之间保存 redux 状态?

javascript - 使用 Redux 在 ExtReact 中首次渲染之前无法从存储加载数据;

reactjs - react |多个动态选择框的单个onchange方法

python - 将多个键与 LRUCache 一起使用

c++ - 以下lru代码中的逻辑错误是什么

java - Java中的LRU算法

javascript - 当用户登录时,必须显示注销按钮,但不会立即显示。为什么会发生这种情况?

reactjs - 如何在react redux中使用mapDispatchToProps

Redux thunk dispatch 不返回错误

node.js - [ MongoNetworkError ],当我在 Heroku 上部署时,应用程序无法连接到 mongoDB