我在我的狀態中有2個對象,我通過在請求中傳遞id
來調用通用API來獲取數據。如何使用通用API來調度redux中的多個動作創建器?
以下是我fetch
打電話,而觸發receiveSectionA我的狀態更新部1.第一部分。
export function fetchSection(sectionCode){
return(dispatch,getState,api)=>{
const endPoint = 'url/?sectionCode='+sectionCode
const method = 'GET'
const isAuth = true
const promise = api(endPoint,method,isAuth)
promise
.then(response =>
response.json().then(json => ({
status:response.status ,
json
})
))
.then(
({ status, json }) => {
if(status >= 200 && status < 300) {
const sectionDictionary = utils.convertSectionsToDictionary(camelizeKeys(json))
dispatch(receiveSectionA(sectionDictionary))
}
if (status >= 400) {
//throw error
}
},
err => {
console.log("error"+err);
}
);
}
}
現在我做出同樣的呼籲sectionB其中火災以下內容: -
dispatch(receiveSectionB(sectionDictionary))
現在,因爲上述fetch
通話一樣有什麼辦法可以讓這個通用。我覺得有太多的代碼重複。
我在想切換的情況下派遣基於sectionCode不同的行動,但我有大約20節,我認爲的代碼就會變得很複雜。
有沒有更好的辦法呢?
這看起來很有趣。但你意想不到的結果是什麼? –
答案更新了鏈接..閱讀,學習,忘記...:D –