2

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

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

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

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

1 回答 1

1

重新选择

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

采取以下代码

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

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

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

使用 Redux 中间件去抖动动作

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

这将只允许每n毫秒触发一个动作

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

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 
  );
};
于 2017-09-08T10:49:46.970 回答