我正在使用 typescript-fsa
和 typescript-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-thunk和 redux-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-thunk和 typescript-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/