简体   繁体   English

用Typescript反应Redux-Thunk

[英]React Redux-Thunk with Typescript

So I am trying to type my Redux Actions with Redux Thunk 所以我想用Redux Thunk输入Redux Actions

Here is an Action 这是一个动作

export function logout() {
  return async(dispatch) => {
    try {
      const value = localStorage.removeItem("token");

      dispatch(cons.updateLoginStatus(false));

      return true;

    } catch (err) {
      console.error(err);
    }
  }
}

Here is the connect file 这是连接文件

const mapStateToProps = (store: IAppState) => {
  return {
    isLoggedIn: store.employee.isLoggedIn
  }
}

const mapDispatchToProps = {
  logout
}

export default connect(mapStateToProps, mapDispatchToProps)(Auth);

When I call await this.props.logout(); 当我打电话await this.props.logout(); I would like to access the returned true But typescript only sees the function being returned. 我想访问返回的true但是打字稿只能看到返回的函数。

So how do I type the function to await for returned value? 那么,如何键入该函数以await返回值?

Or is there any better way to do this? 还是有更好的方法来做到这一点?

What you're attempting seems a bit, anti-pattern. 您尝试的内容似乎有点反模式。 The function is meant to be fire and forget, so that you don't hang the UI. 该功能本来就是一劳永逸的,所以您不必挂起UI。 The login function should dispatch to your reducer that state has now gone from 登录功能应将状态从

loggedIn: false

to

loggedIn: true

If you need some magic with response aka throw an exception if login fails, then I would recommend something like 如果您需要一些魔术,也可以在登录失败时抛出异常,那么我建议您使用类似

this.props.login().catch(err => console.log(err)).then(() => doSomething));

However, I strongly recommend you just dispatch and listen to ComponentDidUpdate lifecycle hook to redirect or whatever you may need to do. 但是,我强烈建议您仅调度并侦听ComponentDidUpdate生命周期挂钩以进行重定向或可能需要执行的任何操作。

您需要通过调度适当的操作来调用注销功能

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

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