我正在使用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的响应到达时调度对调度下一个操作的操作时,我可以发送请求。我想用promises。 怎么解决?
答案 0 :(得分:1)
在没有typescript-fsa
抽象的React中,你会在动作创建者级别进行异步API调用,因为动作只是调度POJO和reducers应该没有任何副作用。
有两个项目可以轻松完成此任务,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回购。