1. /*
    2. * @Author: zhudongguang
    3. * @Date: 2022-02-16 14:47:49
    4. * @LastEditTime: 2022-03-03 12:35:49
    5. * @数据流向为 页面 dispath ==> Service ==> Effects ==> Reducers ==> 页面
    6. */
    7. // const model = {
    8. // namespace: '', model的命名空间
    9. // state: {}, 初始仓库
    10. // reducers: {}, 处理同步数据的函数
    11. // effects: {}, 处理异步数据的函数
    12. // Subscription: {}, 订阅数据源
    13. // };
    14. // export default model;
    15. import { Effect, ImmerReducer, Subscription } from 'umi';
    16. import * as namespaces from '@/constants/namespaces';
    17. export interface DemoModalState {
    18. name: string;
    19. }
    20. export interface DemoModelType {
    21. // namespace命名空间,相当于给model取个名字,但是各个model的namespce是不能重复的
    22. namespace: string;
    23. // state是数据仓库,就是存数据的地方,model里的数据都是存放在这里的
    24. state: DemoModalState;
    25. // 异步方法,简单来说我们的异步请求就写在这里
    26. effects?: {
    27. query?: Effect;
    28. asyncGetData: Effect;
    29. };
    30. // reducers把数据存到仓库(存到state)里的唯一方法,我们修改state里的数据不能直接像this.name='liu'这样去修改,而必须通过调用reducers里的方法
    31. reducers: {
    32. save: ImmerReducer<DemoModalState>;
    33. // state 为上次state的值,action 为触发payload中的值
    34. getList: (state: DemoModalState, action: any) => any;
    35. };
    36. // 订阅,比如监听页面,监听到进入了某某页面就让它执行相关代码之类的
    37. subscriptions: { setup: Subscription };
    38. }
    39. const data = [
    40. {
    41. key: '1',
    42. name: 'John Brown',
    43. age: 32,
    44. address: 'New York No. 1 Lake Park',
    45. tags: ['nice', 'developer'],
    46. },
    47. {
    48. key: '2',
    49. name: 'Jim Green',
    50. age: 42,
    51. address: 'London No. 1 Lake Park',
    52. tags: ['loser'],
    53. },
    54. ];
    55. const DemoModel: DemoModelType = {
    56. namespace: namespaces.DEMO,
    57. state: {
    58. name: '',
    59. },
    60. effects: {
    61. // *query({payload}, {call put}) {},
    62. *asyncGetData(action, effects) {
    63. const listData = yield Promise.resolve(data);
    64. // 如果想用实际接口拿到数据需要调用call
    65. // const { data } = yield effects.call(remoteApi)
    66. // 用effects.put 把数据推给reducers, 并触发getList 函数
    67. yield effects.put({ type: 'getList', payload: listData });
    68. },
    69. },
    70. reducers: {
    71. save(state, action) {
    72. state.name = action.payload;
    73. },
    74. getList(state, action) {
    75. return { listData: action.payload };
    76. },
    77. },
    78. subscriptions: {
    79. setup({ dispatch, history }) {
    80. // dispatch({ type: 'asyncGetData' });
    81. // return history.listen(({ pathname }) => {
    82. // if(pathname === '/home') {
    83. // dispatch({ type: 'demo/getList' })
    84. // }
    85. // })
    86. },
    87. },
    88. };
    89. export default DemoModel;