【问题标题】:How to make API calls using React, Redux in TypeScript如何在 TypeScript 中使用 React、Redux 进行 API 调用
【发布时间】:2018-04-24 19:00:45
【问题描述】:

我正在使用 typescript-fsa 和 typescript-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 的响应到达时,我可以在组件调度下一个动作时发送请求。我想使用承诺。 如何解决?

【问题讨论】:

标签: reactjs typescript promise redux


【解决方案1】:

在没有typescript-fsa 抽象的 React 中,您将在动作创建者级别进行异步 API 调用,因为动作只是被分派的 POJO,reducer 应该没有任何副作用。

有两个项目可以很容易地做到这一点,redux-thunk 和 redux-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-thunk 和 typescript-fsa-redux-saga。

似乎typescript-fsa-redux-thunk 采用了与上述示例类似的方法,使用“动作工作者”的概念,它通过typescript-fsa 协调动作的调度。 on the typescript-fsa-redux-thunk repo 有一个很好的例子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2020-05-16
    • 2020-05-07
    • 1970-01-01
    • 2019-11-29
    • 2019-08-18
    • 2020-05-30
    相关资源
    最近更新 更多