簡體   English   中英

如何從傳遞給Redux Thunk的Redux Action中訪問異步功能?

[英]How to access async function from Redux Action passed into Redux Thunk?

我試圖將代碼從Javascript React重構為Typescript React。

我這里有一個執行API調用並返回帶有dispatch功能的動作

我的UserActions.ts文件看起來像這樣

export const login = ({username, password}) => async (dispatch: any) => {
  try {

    let r = await apiCall(); //performing api call here

    return r.code; //returning the custom responseCode here from my server

    console.log(auth)
  } catch (err) {
    throw new Error(err);
  }
}

在我的組件文件MyComponent.ts有一個組件類的成員函數

public formSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        const { password, email } = this.state;

        this.props.login({
            email,
            password,
        }).then(responseCode => {
                //I want to access responseCode here
        });
}

與Redux的連接在MyComponent.ts看起來像這樣

const mapStateToProps = (store: IAppState) => {
    return {

    }
}

export default connect(mapStateToProps, {
    login
})(SignIn);

因此,如您所見, login實際上返回了一個函數,該函數傳遞到Redux Thunk中間件中,然后在this.props傳遞給MyComponent

要從函數訪問返回變量,我必須在登錄操作UserActions.ts type外部函數。

那么,如何使用正確的類型進行訪問? 因為打字稿不允許我將this.props.login().then()放在MyComponent.ts

最佳實踐是調度操作並將數據填充到reducer。 盡量避免將數據從異步函數傳回。 您可以擁有AuthReducer並更新數據,然后直接在組件中使用它。

export const login = ({username, password}) => async (dispatch: any) => {
    let r = await apiCall(); //performing api call here
    dispatch({ type: 'UPDATE_AUTH', payload: auth })
}

和你的減速器

case 'UPDATE_AUTH':
 return { ...state, ...action.payload }

並在您的組件中

const mapStateToProps = ({ auth }) => ({ auth })

export default connect(mapStateToProps, {
    login
})(SignIn);

我不知道實際的Typescript方法,所以我使用了any解決方法

而不是做

this.props.login({
            email,
            password,
        }).then(responseCode => {
                //I want to access responseCode here
        });

你可以做

const responseCode:any = await this.props.login({email, password});

Typescript await這里檢查await ,我將返回的對象強制轉換為any對象,並且在運行時實際responseCode是從Redux Thunk返回的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM