To provide you with ideas, you can learn from Ha, if you have any questions, you can leave a comment on the
taro scaffolding. The article will slowly explain more skills
https: //github.com/wsdo/taro -...
Overview
When we got the official action of project requests
you need to write two functions (a return type, a dispatch), super trouble, as shown below.
function articleList(data) {
return { type: LIST, payload: data }
}
export function list() {
console.log('list')
return (dispatch) => {
Taro.request({
url: 'http://api.shudong.wang/v1/article/list',
data: {
foo: 'foo',
bar: 10
},
header: {
'content-type': 'application/json'
}
}).then((res) => {
dispatch(articleList(res.data.article)) // 需要在另一个函数 dispatch
})
}
}
If every function is written like this, it will be extremely painful and a lot of redundant code, so how should we design it?
design
- Parameters: type type, function (automatic dispatch)
After this design, we can use actions extremely simply
/**
* 创建API Action
*
* @export
* @param actionType Action类型
* @param [func] 请求API方法,返回Promise
* @returns 请求之前dispatch { type: ${actionType}_request }
* 请求成功dispatch { type: ${actionType}, payload: ${resolveData} }
* 请求失败dispatch { type: ${actionType}_failure, payload: ${rejectData} }
*/
export function createApiAction(actionType, func = () => {}) {
return (
params = {},
callback = { success: () => {}, failed: () => {} },
customActionType = actionType,
) => async (dispatch) => {
try {
dispatch({ type: `${customActionType }_request`, params });
const data = await func(params);
dispatch({ type: customActionType, params, payload: data });
callback.success && callback.success({ payload: data })
return data
} catch (e) {
dispatch({ type: `${customActionType }_failure`, params, payload: e })
callback.failed && callback.failed({ payload: e })
}
}
}
Minimal use
With the encapsulated API asynchronous action described in the previous article, it has become so simple
import { createApiAction } from './index'
export const list = createApiAction(LIST, params => api.get('news/list', params))
All codes
If you can help you, help me order a star
https: //github.com/wsdo/taro -...