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

时间:2017-11-11 18:48:10

标签: reactjs typescript promise redux

我正在使用typescript-fsatypescript-fsa-reducers个包来简单地在TypeScript React应用程序中创建动作和缩减器。

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的响应到达时调度对调度下一个操作的操作时,我可以发送请求。我想用promises。 怎么解决?

1 个答案:

答案 0 :(得分:1)

在没有typescript-fsa抽象的React中,你会在动作创建者级别进行异步API调用,因为动作只是调度POJO和reducers应该没有任何副作用。

有两个项目可以轻松完成此任务,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回购。