Reducer拆分

  • Post author:
  • Post category:其他

看到Redux官网上Reducer拆分后,最后生成的state的组合有点懵,主要是对combineReducers()这个工具类不了解,其实该方法是消除了一些样板代码。

todoApp事例:

import { combineReducers } from 'redux'

const todoApp = combineReducers({
  visibilityFilter,
  todos
})

export default todoApp
复制代码

上面的写法跟下面完全等价:

export default function todoApp(state = {}, action) {
  return {
    visibilityFilter: visibilityFilter(state.visibilityFilter, action),
    todos: todos(state.todos, action)
  }
}
复制代码

你也可以给它们设置不同的 key,或者调用不同的函数。下面两种合成 reducer 方法完全等价:

const reducer = combineReducers({
  a: doSomethingWithA,
  b: processB,
  c: c
})
复制代码
function reducer(state = {}, action) {
  return {
    a: doSomethingWithA(state.a, action),
    b: processB(state.b, action),
    c: c(state.c, action)
  }
}
复制代码