繁体   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