2017-11-11 182 views
0

我使用typescript-fsatypescript-fsa-reducers包簡單地在TypeScript React應用程序中創建動作和縮減器。如何在TypeScript中使用React,Redux進行API調用

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響應到達時,組件分派調度下一個動作時發送請求。我想用承諾。 如何解決?

+0

你見過'typescript-fsa'中的異步操作文檔嗎? https://github.com/aikoven/typescript-fsa#async-action-creators –

+0

是的,但我不知道應該在哪裏進行API調用。行動,行動創造者還是減速器?我想看一個例子 – micnyk

回答

1

在沒有typescript-fsa抽象的React中,您會在動作創建者級別上創建異步API調用,因爲動作只是分派了POJO和減速器應該沒有任何副作用。

有兩個項目很容易做到這一點,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回購的一個很好的例子。

相關問題