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
87 声望4 粉丝