Javascript 为api调用创建包装函数时遇到问题
所以本质上我有一个模式,我希望在我的api调用中使用它。它本质上是一个Javascript 为api调用创建包装函数时遇到问题,javascript,reactjs,react-native,redux,axios,Javascript,Reactjs,React Native,Redux,Axios,所以本质上我有一个模式,我希望在我的api调用中使用它。它本质上是一个try-catch-finally块,我在其中分派一系列操作。我不想到处复制和粘贴这个模式,而是想创建一个包装器函数,其中传入的是必要的参数、api函数和分派操作 我的try call block函数如下所示: 导出函数getTokenAPI(用户名、密码){ 返回异步函数操作(分派){ 试一试{ 分派(loadingActions.LoadingProgress(true)); const{data}=await API.a
try-catch-finally
块,我在其中分派一系列操作。我不想到处复制和粘贴这个模式,而是想创建一个包装器函数,其中传入的是必要的参数、api函数和分派操作
我的try call block函数如下所示:
导出函数getTokenAPI(用户名、密码){
返回异步函数操作(分派){
试一试{
分派(loadingActions.LoadingProgress(true));
const{data}=await API.authGetToken(用户名、密码);
const{success}=数据;
log('获取令牌api数据',数据);
如果(成功){
调度(设置数据(数据));
调度(setTokenSuccess());
}否则,如果(!成功){
const{errorMessage}=数据;
抛出错误(errorMessage | |“你弄坏了,不是我的错”);
}
}捕获(e){
发送(错误动作。添加错误(e.message));
分派(errorActions.removeError());
}最后{
调度(加载操作。加载进度(错误));
}
};
}
因此,我尝试创建的包装器如下所示:
函数包装器(apiffunction,dispatchAction){
返回异步函数操作(分派){
试一试{
分派(loadingActions.LoadingProgress(true));
const{data}=等待函数(arg1,arg2);
const{success}=数据;
如果(成功){
调度(调度动作(数据));
}否则,如果(!成功){
const{errorMessage}=数据;
抛出错误(errorMessage | | meh');
}
}捕获(e){
发送(错误动作。添加错误(e.message));
分派(errorActions.removeError());
}最后{
调度(加载操作。加载进度(错误));
}
};
}
有了这些,我终于可以跑了
wrapper(apiFunction(username, password), setData)
但是我得到一个类型错误,无法读取未定义的属性类型。我想知道我的做法是否正确
任何建议或建议?包装器
是一个高阶函数
,它需要两个参数apiffunction
和dispatchAction
和return
一个动作创建者
,它需要一个动作,并且必须包装在调度
实例中。所以你应该像这样使用包装器
const Component = () =>{
const dispatch = useDispatch()
const onSubmit = () =>{
dispatch(wrapper(apiFunction, dispatchAction)(action))
}
}
wrapper(apiffunction,dispatchAction)
计算为另一个函数,该函数需要一个参数操作
并需要显式执行。相当于
const onSubmit = () =>{
const actionCreator = wrapper(apiFunction, dispatchAction)
dispatch(actionCreator(action))
}
因此,我通过编辑我的包装,并使用Dupocas的答案作为灵感(需要使用dispatch),解决了这个问题
这是我的包装纸,这是我如何使用它的:
apiWrapper
import{loadingActions}来自“_ducks/loading”;
从“_/error”导入{errorActions}”;
从“react native”导入{Platform};
常量os=平台==='ios'?'iPhone':'Android';
const{loadingprogress}=loadingActions;
const{addError,removeError}=errorActions;
导出默认函数apiWrapper(
apiFunction,
dispatchActionData,
调度状态,
) {
返回异步函数操作(分派){
试一试{
调度(加载进度(真实));
const{data}=等待函数;
const{success}=数据;
console.log('data',数据);
如果(成功){
dispatchActionData和dispatch(dispatchActionData(data));
dispatchActionStatus&&dispatch(dispatchActionStatus());
}否则,如果(!成功){
const{errorMessage}=数据;
抛出错误(
errorMessage | | `听起来您的${os}设备有问题`,
);
}
}捕获(e){
调度(添加错误(e.message));
分派(removeError());
}最后{
调度(加载进度(错误));
}
};
}
使用apiWrapper
export function submitLogIn(username, password) {
return function action(dispatch) {
dispatch(
apiWrapper(
API.getSTUFF(username, password),
setUserData,
setTokenSuccess,
),
);
};
}