在我的react/redux/thunk应用程序中,我使用以下操作:
function catsRequested() {
return {
type: CATS_REQUESTED,
payload: {},
};
}
function catsReceived(landings) {
return {
type: CATS_RECEIVED,
payload: landings,
};
}
function catsFailed(error) {
return {
type: CATS_FAILED,
payload: { error },
};
}
export const fetchCats = () => ((dispatch, getState) => {
dispatch(catsRequested());
return catsAPI.loadCats()
.then((cats) => {
dispatch(catsReceived(cats));
}, (e) => {
dispatch(catsFailed(e.message));
});
});
Run Code Online (Sandbox Code Playgroud)
处理一些数据(简化).一切正常但我有很多代码用于每个数据实体(以及常量).我的意思是狗,老虎,鸟等相同的功能......
我看到每个实体都有类似的请求/接收/失败动作/常量.
什么是使用redux-thunk缩小代码的正确方法?
您可以通过创建类型和thunk创建者来保持代码DRY:
类型:
const createTypes = (type) => ({
request: `${type}_REQUESTED`,
received: `${type}_RECEIVED`,
failed: `${type}_FAILED`,
});
Run Code Online (Sandbox Code Playgroud)
咚:
const thunkCreator = (apiCall, callTypes) => ((dispatch, getState) => {
dispatch({ type: callTypes.request });
return apiCall
.then((payload) => {
dispatch({ type: callTypes.received, payload }));
}, (e) => {
dispatch({ type: callTypes.failed, payload: e.message }));
});
});
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用2行代码创建一个fetch方法:
export const fetchCatsTypes = createTypes('CATS'); // create and export the constants
export const fetchCats = (catsAPI.loadCats, fetchCatsTypes); // create and export the thunk
export const fetchDogsTypes = createTypes('DOGS'); // create and export the constants
export const fetchDogs = (dogsAPI.loadDogs, fetchDogsTypes ); // create and export the thunk
Run Code Online (Sandbox Code Playgroud)
注意:您还将fetchDogsTypes在reducers中使用constant()类型.
| 归档时间: |
|
| 查看次数: |
312 次 |
| 最近记录: |