【发布时间】:2016-10-25 16:03:01
【问题描述】:
我的状态中有 2 个对象,我通过在请求中传递 id 来调用一个通用 API 来获取数据。
以下是我的 fetch 调用第一个 Section,它触发 receiveSectionA 以更新我所在州的 sectionA。
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 个部分,我认为代码会变得非常复杂。
有没有更好的处理方法?
【问题讨论】: