dva.png

reducers

reducers同步方法的实现,app.model的原理

  1. app.model({
  2. namespace: 'counter',
  3. state: { number: 0 },
  4. // 同步的方法
  5. reducers: {
  6. // state是之前的状态,return返回值是新状态 state
  7. add(state, action) {
  8. window.console.log('action', action);
  9. return { number: state.number + (action.payload || 10) };
  10. },
  11. minus(state) {
  12. return { number: state.number - 2 };
  13. },
  14. },
  15. });

app._models

  1. [
  2. {
  3. namespace: 'counter',
  4. state: { number: 0 },
  5. // 同步的方法
  6. reducers: {
  7. // state是之前的状态,return返回值是新状态 state
  8. add(state, action) {
  9. window.console.log('action', action)
  10. return { number: state.number + (action.payload || 10) }
  11. },
  12. minus(state) {
  13. return { number: state.number - 2 }
  14. },
  15. },
  16. },
  17. {
  18. namespace: 'list',
  19. state: { number: 0 },
  20. reducers: {
  21. // state是之前的状态,return返回值是新状态 state
  22. add(state, action) {
  23. window.console.log('action', action)
  24. return { number: state.number + (action.payload || 10) }
  25. },
  26. minus(state) {
  27. return { number: state.number - 2 }
  28. },
  29. },
  30. }
  31. ]

app.model的实现

  1. import { combineReducers, createStore } from 'redux';
  2. function createReducers(app) {
  3. const rootReducers = {}
  4. for(const model of app._models) {
  5. const {namespace, reducers } = model;
  6. // state要有一个初始化的值
  7. // action = dispatch({ type: 'counter/add' })
  8. rootReducers[namespace] = (state = model.state, action) => {
  9. // action.type: 'counter/add'
  10. const [namespace: name, type] = action.type.split('/');
  11. // 判断命名空间
  12. if(namespace === name) {
  13. // 当前命名空间下,是否有这个属性,有这个函数就调用
  14. const reducer = reducers[type];
  15. if(reducer) return reducer(state, action);
  16. }
  17. return state;
  18. }
  19. }
  20. return combineReducers(rootReducers);
  21. }

app.start

createStore

  1. const rootReducers = createReducers(app);
  2. createStore(rootReducers);