關於react中antd design pro下面src/models

1.src/models

  在 Ant Design Pro 中,一個完整的前端 UI 交互到服務端處理流程是這樣的:

  1.UI 組件交互操作;

  2.調用 model 的 effect;


  3.調用統一管理的 service 請求函數;


  4.使用封裝的 request.ts 發送請求;


  5.獲取服務端返回;


  6.然後調用 reducer 改變 state;


  7.更新 model。

1 // model
2 {
3   namespace: String, // 命名空間
4   state: Object, // 狀態
5   reducer: Object, // 同步更新 state
6   effects: Object, // 副作用:處理非同步邏輯
7   subscriptions: Object // 訂閱數據源
8 } 

  這些文件被引用在src/pages/.umi/dva中。

  我們以 models/global 為例:

  namespace: 'global' 說明以下此處的dva命名空間為 global,即你調用的時候需要採用 global.XXX 的形式

  其中的 state: {} 是存放狀態的,也就是數據。

  reducers 是用來更新 state 的,但是他只能是同步的。所以我們需要 effects 來進行非同步更新。

  即:

 1 state: {
 2 collapsed: false,
 3 notices: [],
 4 }, // 存放狀態和數據
 5   reducers: { // 用來同步設置state
 6     changeLayoutCollapsed(
 7       state = {
 8         notices: [],
 9         collapsed: true,
10       },
11       { payload },
12     ) {
13       return { ...state, collapsed: payload };
14     },
15 
16     saveNotices(state, { payload }) {
17       return {
18         collapsed: false,
19         ...state,
20         notices: payload,
21       };
22     },
23     // ...
24  }
 1   effects: { // 非同步更新state,通過調用同步的reducers實現
 2     *fetchNotices(_, { call, put, select }) {
 3       const data = yield call(queryNotices);
 4       yield put({
 5         type: 'saveNotices',
 6         payload: data,
 7       });
 8       const unreadCount = yield select(
 9         state => state.global.notices.filter(item => !item.read).length,
10       );
11       yield put({
12         type: 'user/changeNotifyCount',
13         payload: {
14           totalCount: data.length,
15           unreadCount,
16         },
17       });
18     },
19     // ...
20  }

 

 

Tags:
Exit mobile version