简体   繁体   English

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

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

I am trying to refactor code from Javascript React to Typescript React. 我试图将代码从Javascript React重构为Typescript React。

I have an action here which performs an API call and returns a function with dispatch 我这里有一个执行API调用并返回带有dispatch功能的动作

My UserActions.ts file looks like this 我的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);
  }
}

In my component file MyComponent.ts there is a member function for the component class 在我的组件文件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
        });
}

The connection to Redux looks like this in MyComponent.ts 与Redux的连接在MyComponent.ts看起来像这样

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

    }
}

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

So, as you can see, the login actually returns a function which is passed into Redux Thunk Middleware and is then passed in this.props to MyComponent 因此,如您所见, login实际上返回了一个函数,该函数传递到Redux Thunk中间件中,然后在this.props传递给MyComponent

To access return variable from function, I have to type the outer function in login action UserActions.ts . 要从函数访问返回变量,我必须在登录操作UserActions.ts type外部函数。

So how do I access with proper types ? 那么,如何使用正确的类型进行访问? Because typescript won't allow me to put this.props.login().then() in MyComponent.ts 因为打字稿不允许我将this.props.login().then()放在MyComponent.ts

The best practise is to dispatch action and populate the data to reducer. 最佳实践是调度操作并将数据填充到reducer。 Try to avoid passing data back from async functions. 尽量避免将数据从异步函数传回。 You can have a AuthReducer and update the data and use it directly in the component. 您可以拥有AuthReducer并更新数据,然后直接在组件中使用它。

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

and in your reducer 和你的减速器

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

and in your component 并在您的组件中

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

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

I didn't know the actual Typescript way to do it, so I used the any workaround 我不知道实际的Typescript方法,所以我使用了any解决方法

Instead of doing 而不是做

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

You can just do 你可以做

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

Typescript is checking await here and I'm casting the returned object to any and in runtime the actual responseCode is returned from Redux Thunk Typescript await这里检查await ,我将返回的对象强制转换为any对象,并且在运行时实际responseCode是从Redux Thunk返回的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM