reactjs - 如何在 TypeScript 中使用 React、Redux 进行 API 调用

标签 reactjs typescript promise redux

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

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 调用,因此我可以在组件分派(dispatch) Action 时发送请求,当来自 API 的响应到达时分派(dispatch)下一个 Action 。我想使用 promise 。 怎么解决?

最佳答案

在没有 typescript-fsa 抽象的 React 中,您将在 action creator 级别进行异步 API 调用,因为 action 只是分派(dispatch)的 POJO,reducer 应该没有任何副作用。

有两个项目可以轻松做到这一点,redux-thunkredux-saga .我更喜欢 redux-thunk 因为它更容易绕过你的头。基本上你的 Action 创建者通过了 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 似乎采用了与上述示例类似的方法,使用“action worker”的概念,它通过 typescript 协调 Action 的调度-fsa。有一个很好的例子可以做到这一点 on the typescript-fsa-redux-thunk repo 。

关于reactjs - 如何在 TypeScript 中使用 React、Redux 进行 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47241576/

相关文章:

javascript - promise 没有以我期望的方式解决

javascript - ReactJS onClick ReactCSSTransitionGroup 动画

angular - 为什么异步管道的新数据不会导致数据重新渲染?

mysql - 如何在 ExpressJs 上加载静态图像

angular - 我需要通过路由器导出激活方法在路由器导出中获取组件名称

node.js - 如何将 mongo 的 .native 函数转化为 bluebird Promise?

javascript - 如何渲染组件以支持 React/Redux(正确的方法)?

javascript - VS Code 中来自具有导入的类型定义的 javascript 文件的智能感知

javascript - 在 Angular rxjs 中寻找类似 OrElse 的东西在管道时查找函数

javascript - 使用 extends 子类化 Promise 内置