UNPKG

ola-toolkit

Version:

ola 开发工具套件

119 lines (83 loc) 2.65 kB
# ReduxCreator 通用 action type 与 reducer 创建器 在大多数场景中,异步请求数据的周期具有极高的相似度,其过程可以归纳为:发起请求、响应成功、响应失败、更新、清除, 并且在这些场景中,它们常常具备一致的数据处理行为,ReduxCreator 整合了这些规律以避免过多的模板代码。 ## 使用 创建 actionTypes 与 reducer ```javascript import {ReduxCreator} from 'ola-toolkit'; export const DocsTypes = ReduxCreator.createAsyncActionTypes('docs'); export const docs = ReduxCreator.createBasicReducer(DocsTypes); ``` 使用(以 saga 为例) ```javascript export function* fetchDocs({payload: params}) { yield put({ type: DocsTypes.fetch, payload }); try { const payload = yield call(Ajax.get, {params}); yield put({ type: DocsTypes.success, payload }); } catch (e) { yield put({ type: DocsTypes.fail, payload: e }); } } export default combineReducers({ docs, }); ``` ## 部件 ### Action Types | type | 说明 | | --- | --- | | fetch | 发送 GET 请求 | | success | 发送 POST 请求 | | update | 全局配置 | | fail | 全局配置 | | clear | 全局配置 | ### reducer 对于每个异步请求,其在 store 中 包含 loaded / loading / payload / error 四个节点,分别表示该请求是否装载完成 / 是否处于加载中 / 实际响应数据 / 异常信息 其对应的 action type 时值的关系如下: | - | fetch | success | update | fail | clear | |---------|-------|----------------|----------------|----------------|-------| | loaded | false | true | true | false | false | | loading | true | false | false | false | false | | payload | init | action.payload | action.payload | state.payload | init | | error | null | null | null | action.payload | null | ```javascript const init = Map({ loaded: false, loading: false, error: null, payload: Map({ page: Map() }) }); ``` ## API ### createAsyncActionTypes 创建 action types ``` ActionTypes createAsyncActionTypes(String key) ``` `key`: 唯一标识 ### createBasicReducer 创建基础 reducer ``` void createBasicReducer(ActionTypes actionTypes) ``` ### createExtensibleReducer 创建内容可扩展的 reducer (用于无限加载等类似场景) ``` void createExtensibleReducer(ActionTypes actionTypes, keys[]) ``` `keys`: 要扩展的字段信息 `keys[].key`: 要扩展的字段名 `keys[].type`: 要扩展的字段数据类型: Array / Object