如何在TypeScript中使用React,Redux进行API调用

如何在TypeScript中使用React,Redux进行API调用

问题描述:

我使用typescript-fsatypescript-fsa-reducers包简单地在TypeScript React应用程序中创建动作和缩减器。如何在TypeScript中使用React,Redux进行API调用

const actionCreator = actionCreatorFactory(); 

export function signInHandler(state: UserState, action: Action): UserState { 
    // ???? 

    return { ...state }; 
} 

export const signIn = actionCreator.async<SignInRequest, RequestResponse<SignInResponse>>("USER_SIGNIN"); 

export const UserReducer = reducerWithInitialState({ signedIn: false } as UserState) 
    .casesWithAction([signIn.started, signIn.done], signInHandler) 
    .build(); 

用法在组件:

export default connect<StateProps, DispatchProps>(
    (state: RootState) => ({} as StateProps), 
    (dispatch: Dispatch<RootState>) => { 
    return { 
       signIn: (userName: string, password: string) => dispatch(signIn.started(new SignInRequest(userName, password))) 
    }; 
    } 
)(SignIn); 

现在我卡住了。我不知道如何对我的API进行HTTP调用,以便在API响应到达时,组件分派调度下一个动作时发送请求。我想用承诺。 如何解决?

+0

你见过'typescript-fsa'中的异步操作文档吗? https://github.com/aikoven/typescript-fsa#async-action-creators –

+0

是的,但我不知道应该在哪里进行API调用。行动,行动创造者还是减速器?我想看一个例子 – micnyk

在没有typescript-fsa抽象的React中,您会在动作创建者级别上创建异步API调用,因为动作只是分派了POJO和减速器应该没有任何副作用。

有两个项目很容易做到这一点,redux-thunkredux-saga。我更喜欢redux-thunk,因为它更容易缠绕头部。基本上,你的行动的创作者获得通过的dispatch功能,然后他们可以负责调度不止一件事......像这样:

function asyncActionCreator(dispatch) { 
    dispatch(startAsyncAction()); 

    doSomethingAsync() 
    .then(result => dispatch(completeAsyncAction(result)) 
    .catch(err => dispatch(errorAsyncAction(err)); 
} 

在你typescript-fsa的世界里,也有一些同伴包为这两种: typescript-fsa-redux-thunktypescript-fsa-redux-saga

看起来typescript-fsa-redux-thunk采用与上述示例类似的方法,使用“动作工作者”的概念,该动作工作者通过typescript-fsa协调动作的分派。有这样做on the typescript-fsa-redux-thunk回购的一个很好的例子。