Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

高阶reducer #16

Open
xiaoxiaosaohuo opened this issue Nov 5, 2017 · 0 comments
Open

高阶reducer #16

xiaoxiaosaohuo opened this issue Nov 5, 2017 · 0 comments

Comments

@xiaoxiaosaohuo
Copy link
Owner

高阶函数是指将函数作为参数或返回值的函数,高阶reducer就是指将reducer作为参数或返回值的函数。目的是reducer复用

例1:

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

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

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

export default rootReducer




例2:


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

const add = section => reducer => (state, action) => {
  if (action.type === `ADD_${section}`) {
    return [...state, action.payload]
  }
  return reducer(state, action)
}

const remove = section => reducer => (state, action) => {
  if (action.type === `REMOVE_${section}`) {
    return state.filter(item => item !== action.payload)
  }
  return reducer(state, action)
}

const sectionReducer = section => compose(add(section), remove(section))

const rootReducer = combineReducers({
  users: sectionReducer("USER")(users),
  articles: sectionReducer("ARTICLE")(articles)
})

export default rootReducer

users.js

//users.js

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

    default:
      return state
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant