effects文档 https://dvajs.com/api/#effects

effects的里面的异步函数参数为:

  1. *(action, effects) => void
  2. [*(action, effects) => void, { type }]

image.png
/models/index.js

  1. export default {
  2. namespace: 'home',
  3. state: {},
  4. reducers: {},
  5. effects: {
  6. *asyncTable(action, effects) {},
  7. *asyncTable({payload}, {put, yield, select}) {},
  8. // 删除
  9. *remove({ payload: id }, { call, put, select }) {
  10. yield call(usersService.remove, id);
  11. const page = yield select(state => state.users.page);
  12. // put 等价于 dispatch action重新获取数据
  13. yield put({ type: 'fetch', payload: { page } });
  14. },
  15. }
  16. }

select

select(state => state)) ,state默认是所有的 state

  1. *asyncTable(action, {call, put, select }) {
  2. // 全局的 state
  3. const state = yield select(state => state);
  4. // 当前的 state
  5. const state = yield select(state => state.home);
  6. },

image.png

subscriptions

  1. import * as usersService from '../services/users';
  2. export default {
  3. namespace: 'users',
  4. state: {
  5. list: [],
  6. total: null,
  7. },
  8. reducers: {
  9. save(state, { payload }) {
  10. const { data: list, total } = payload;
  11. return { ...state, list, total };
  12. },
  13. },
  14. effects: {
  15. *fetch({ payload: { page } }, { call, put }) {
  16. // 请求接口
  17. const { data, headers } = yield call(usersService.fetch, { page });
  18. // action
  19. yield put({
  20. type: 'save',
  21. payload: { data, total: headers['x-total-count'] }
  22. });
  23. },
  24. },
  25. subscriptions: {
  26. setup({ dispatch, history }) {
  27. // 监听路由,自动请求数据
  28. return history.listen(({ pathname, query }) => {
  29. if (pathname === '/users') {
  30. dispatch({ type: 'fetch', payload: query });
  31. }
  32. });
  33. },
  34. },
  35. };

在 subscriptions 中订阅路由变化,再通过 action 去重置状态会更合适
umi+dva完成 crud
https://github.com/sorrycc/blog/issues/62
https://github.com/umijs/umi-example-dva-user-dashboard

routerRedux

  1. dispatch(routerRedux.push({
  2. pathname: '/users',
  3. query: { page },
  4. }));