js手札--redux简朴进修(二)

redux简朴进修(二)

redux简朴进修[ store, action, reducer ]

1. combineReducers

combineReducers,兼并多个reducer

若有下面两个reducer,todoApp,textApp

// reducers/todoApp.js

export default function todoApp(state, action) {
  switch (action.type) {
    case 'add':
      return Object.assign({}, state, {
          result : action.a + action.b
      })
    case 'sub':
      return Object.assign({}, state, {
          result : action.a - action.b
      })
    default:
      return state
  }
}
// reducers/textApp.js

export default function todoApp(state, action) {
  switch (action.type) {
    case 'normal':
      return Object.assign({}, state, {
          result : action.text
      })
    case 'camel':
      return Object.assign({}, state, {
          result : action.text.replace(/-[^-]{1}/g, (m) => m[1].toUpperCase())
      })
    default:
      return state
  }
}

换成combineReducers,则为

// reducers/index.js

import { combineReducers } from 'redux';
import textApp from './textApp';
import todoApp from './todoApp';

export default combineReducers({
  textApp,
  todoApp
});

则调用时能够写成如许

import reducer from './reducers'

let store = createStore(reducer);
    原文作者:foolishq
    原文地址: https://segmentfault.com/a/1190000005345462
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞