如何从传递给Redux Thunk的Redux Action中访问异步功能?

时间:2018-08-18 13:26:28

标签: reactjs typescript redux

我正在尝试将代码从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
        });
}

MyComponent.ts

中,与Redux的连接看起来像这样
const mapStateToProps = (store: IAppState) => {
    return {

    }
}

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

因此,如您所见,login实际上返回一个函数,该函数传递到Redux Thunk中间件中,然后以this.props传递到MyComponent

要访问函数的返回变量,我必须在登录操作typeUserActions.ts外部函数。

那么我该如何使用正确的类型进行访问?因为打字稿不允许我将this.props.login().then()放在MyComponent.ts

2 个答案:

答案 0 :(得分:0)

最佳实践是调度动作并将数据填充到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);

答案 1 :(得分:0)

我不知道实际的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,然后将返回的对象强制转换为any,在运行时,实际的responseCode从Redux Thunk返回了