Redux - 减速器取决于其他状态

时间:2016-09-04 06:21:47

标签: redux

我有一个Redux应用程序,它根据一组过滤器(用户输入)显示属性列表。

我的州的简要说明:

  1. filters - 过滤值对象...
  2. properties - 第页
  3. 上所有可用资源的回购
  4. visibleProperties - 已应用当前过滤器的属性列表
  5. 问题出在我派遣时设置新的过滤器值,我需要根据properties 新状态过滤filters并将结果存储在visibleProperties

    所以我提出了这个解决方案:

    export function setBedroomFilter (value) {
      return (dispatch, getState) => {
    
        // 'SET_FILTER' action
        dispatch(setFilter('bedroom', parseInt(value)))
    
        // New state
        const { filters, properties } = getState()
    
        // 'FILTER_PROPERTIES' action (Depending on new state)
        dispatch(filterProperties(properties, filters))
      }
    }
    

    visibleProperties reducer可以完成它的工作:

    // case 'FILTER_PROPERTIES'...
    visibleProperties = action.properties.filter(item => item.bedroom >= action.filters.bedroom)
    

    这种方法完全没问题吗?

1 个答案:

答案 0 :(得分:1)

来自dispatch的文档:

  

调度操作。这是触发状态变化的唯一方法。

     

将使用当前调用商店的减少功能   getState()结果和给定的动作同步。它的回报价值   将被视为下一个州。它将从getState()返回   从现在开始,将立即通知变更听众。

这是一个同步函数,按照你所描述的方式使用它是完全没问题的(只要setFilter是同步的)。但是,如果您在setFilter中进行异步操作,(假设Promise从setFilter返回),您应该像这样链接调度调用:

dispatch(setFilter('bedroom', parseInt(value))).then(() => {
   // New state
   const { filters, properties } = getState()

   // 'FILTER_PROPERTIES' action (Depending on new state)
   dispatch(filterProperties(properties, filters))
}

另一种选择可能是使用选择器。请检查一下: https://github.com/reactjs/reselect

相关问题