【问题标题】:Redux and Reselect and saving cached dataRedux 和 Reselect 并保存缓存数据
【发布时间】:2016-09-07 05:25:33
【问题描述】:

所以,据我了解 - 重新选择适用于不同状态树部分之间的派生状态,或来自不同减速器的派生状态。但是,如果我有类似的东西怎么办:

<ul>
  <li onClick="this.getItems({id: 122})">Item 1
  <li onClick="this.getItems({id: 342})">Item 2
  <li onClick="this.getItems({id: 8767})">Item 3
  <li onClick="this.getItems({id: 12})">Item 4
</ul>

等.. 基本上,我没有推导出任何状态数据的组合或任何东西,但我想通过提供以前的“请求调用”来“限制”重复操作/reducer 调用。那么,Reselect 对这个有好处吗?如果是这样,任何一般的例子。我见过的例子计算派生状态。我在想一个解决方案是用一个记忆/缓存功能来装饰我的动作,如果有的话,它将交回以前请求的数据,否则,随着动作调用向前移动。即..

@cachedProductItem
export function getItems({id}) {
  // if id is cached, return it from the decorator wrapped component, else
  // call the action
  return {
    type: .....,
    id
  }
}

【问题讨论】:

标签: redux reselect


【解决方案1】:

重新选择

重新选择用于避免基于状态计算的重新渲染

获取以下代码

const mapStateToProps = ({someStateKeys, someEntity}) => {
  return {
    newProp = someStateKeys.map(key => someEntity[key])
  }
}

即使状态没有改变,map 也会返回一个新数组,因此newProp 键将无法通过对象相等性检查并强制重新渲染

reselect memoize 提供的createSelector 函数是在props没有改变的情况下返回相同对象的map,因此不会发生重新渲染

使用 Redux 中间件消除动作

听起来您想要做的可能是限制可以触发操作的速率。

这将只允许每n ms 触发一次操作

一个简单的中间件可能会这样

const pending = {};

const debounceMiddleware = () => next => action => {
  const { debounce } = action.meta || {}; 
  if (!debounce) {
    return next(action);
  }
  if (pending[action.type]) { 
    clearTimeout(pending[action.type]);
  }
  pending[action.type] = setTimeout(
    () => {
      delete pending[action.type];
      next(action);
    },
    debounce 
  );
};

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多