[Redux] Understand Redux Higher Order Reducers

Higher Order Reducers are simple reducer factories, that take a reducer as an argument and return a new reducer. In that new reducer, you can customize the behaviour of the original one which helps reducing the reducer logic.

In this lesson, we‘ll see how to reduce duplicated code by refactoring two different reducers into a higher order reducer.

Reducers:

export default (state = [], { type, payload }) => {
  switch (type) {
     case "ADD_ARTICLE":
       return [...state, payload]

    default:
      return state
  }
}
export default (state = [], { type, payload }) => {
  switch (type) {
     case "ADD_USER":
       return [...state, payload]

    default:
      return state
  }
}

They both share the same code structure.

HOC reducer:

which is a reducer hoc function return a reducer function.

import { combineReducers } from "redux"
import users from "./users"
import articles from "./articles"

const addHoc = (reducer, predicate) => (state, action) => {
  if (predicate(action.type)) {
    return [...state, action.payload]
  }
  return reducer(state, action)
}

const rootReducer = combineReducers({
  users: addHoc(users, type => type === "ADD_USER"),
  articles: addHoc(articles, type => type === "ADD_ARTICLE")
})

export default rootReducer

If match the predicate function, then we can compute the next state and return it. If doesn‘t match, then pass to the reducer normally. Then we can remove "ADD_USER" and "ADD_ARTICLE" cases from reducers.

Personally I don‘t think this is a good approach... even it reduce the boilerplate code, but it decrease the code readability. I still prefer keep all the reducer logic inside the its reducer file. Just make a reuseable function would be better:

export const append = (state, payload) => {
  return [...state, payload]
}

export default (state = [], { type, payload }) => {
  switch (type) {
     case "ADD_USER":
       return append(state, payload)

    default:
      return state
  }
}

It also make Unit testings easier.

时间: 2024-10-10 14:49:35

[Redux] Understand Redux Higher Order Reducers的相关文章

[React] Cleanly Map Over A Stateless Functional Component with a Higher Order Component

In this lesson we'll create a Higher Order Component (HOC) that takes care of the key property that React looks for when using map to create elements from a list. This HOC will allow us to wrap any component and it will take care of placing the keypr

Javascript—Higher Order Functions

Higher order functions are functions that manipulate other functions. For example, a function can take other functions as arguments and/or produce a function as its return value. Such fancy functional techniques are powerful constructs available to y

React-安装和配置redux调试工具Redux DevTools

chrome扩展程序里搜索Redux DevTools进行安装 新建store的时候,进行如下配置. import { createStore, applyMiddleware ,compose} from 'redux'; import reducer from './reducer' import thunk from 'redux-thunk' const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? wi

高阶函数HOF和高阶组件HOC(Higher Order Func/Comp)

一.什么是高阶函数(组件),作用是什么? 子类使用父类的方法可以通过继承的方式实现,那无关联组件通信(redux).父类使用子类方法(反向继承)呢 为了解决类(函数)功能交叉/功能复用等问题,通过传入类/函数返回类/函数(继承)的方式使得类拥有自身未定义的方法. 例如react-redux的connect方法使用了高阶组件: React Redux的connect: const HOC = connnect(mapStateToProps)(Comp); // connect为柯里化函数 实际为

[RxJS] Flatten a higher order observable with concatAll in RxJS

Besides switch and mergeAll, RxJS also provides concatAll as a flattening operator. In this lesson we will see how concatAll handles concurrent inner Observables and how it is just mergeAll(1). const clickObservable = Rx.Observable .fromEvent(documen

[RxJS] Flatten a higher order observable with mergeAll in RxJS

Among RxJS flattening operators, switch is the most commonly used operator. However, it is important to get acquainted with mergeAll, another flattening operator which allows multiple concurrent inner observables. In this lesson we will explore merge

[Redux] Filtering Redux State with React Router Params

We will learn how adding React Router shifts the balance of responsibilities, and how the components can use both at the same time. Now when we click the filter, the url changes, but the todos list doesn't change. So continue with that. Router only r

看漫画,学 Redux

Flux 架构已然让人觉得有些迷惑,而比 Flux 更让人摸不着头脑的是 Flux 与 Redux 的区别.Redux 是一个基于 Flux 思想的新架构方式,本文将探讨它们的区别. 如果你还没有看过这篇关于 Flux 的文章(译者注:也可以参考这篇),你应该先阅读一下. 为什么要改变 Flux? Redux 解决的问题和 Flux 一样,但 Redux 能做的还有更多. 和 Flux 一样,Redux 让应用的状态变化变得更加可预测.如果你想改变应用的状态,就必须 dispatch 一个 ac

Redux生态系统

生态系统 Redux 是一个体小精悍的库,但它相关的内容和 API 都是精挑细选的,足以衍生出丰富的工具集和可扩展的生态系统. 如果需要关于 Redux 所有内容的列表,推荐移步至 Awesome Redux.它包含了示例.样板代码.中间件.工具库,还有很多其它相关内容.要想学习 React 和 Redux ,React/Redux Links 包含了教程和不少有用的资源,Redux Ecosystem Links 则列出了 许多 Redux 相关的库及插件. 本页将只列出由 Redux 维护者