Redux操作后如何重定向

时间:2019-05-07 18:22:25

标签: reactjs react-redux typesafe-actions

我想知道重定向的最佳方法是处理完我的动作之后。在我的操作被触发后,应将用户重定向到'/login'

我正在使用带有以下代码的typesafe-actions

操作

export const Logout = createStandardAction(
  AuthActionTypes.Logout
)<AuthStatus>()

减速器

case getType(actions.Logout):
  return {
    ...state,
    verifyingTokenStatus: ProgressStatus.Uninitialized,
    tokenRefreshStatus: ProgressStatus.Uninitialized,
    authStatus: action.payload,
    tokenStatus: TokenStatus.Uninitialized,
    user: undefined,
    token: undefined,
  }

将操作传递给我的组件

const mapDispatchToProps = (dispatch: Dispatch) => ({
  logout: (authStatus: AuthStatus) => dispatch(Logout(authStatus))
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(({ children, authStatus, user, logout }: Layout & Props<Component>) => (
  <Layout className="layout" style={{ minHeight: '100vh' }}>
      <AuthTopMenu theme={'light'} mode={'horizontal'} user={user} logout={logout} />
  </Layout>
))

AuthTopMenu具有一个头像组件,该组件可以执行注销操作

const removeToken = ({ logout }: AvatarContentProps) => {
  const cookies = new Cookies();
  if (cookies.get('token')) {
    cookies.remove('token')
    logout(AuthStatus.isNotLoggedIn)
  } else {
    return null;
  }
}

const AvatarContent = (logout: AvatarContentProps) => {
  return (
    <div>
      <p style={{ margin: 0 }} onClick={() => removeToken(logout)} >
        <Icon type="logout" />
        Logout
    </p>
    </div>
  );
}

我不确定在执行动作后处理重定向的最佳方法是什么。我看到componentDidUpdate可用于检查我已登录用户的状态是否已更改,但是想知道我的操作是否可以解决此问题?

1 个答案:

答案 0 :(得分:0)

为了重定向/重新路由,您需要使用react-router-dom的{ withRouter }组件,这将使您的组件可以访问props.history。您需要使用它来将一条路线重定向到另一条路线

在您的AvatarContent中:

import { withRouter } from "react-router-dom"

const AvatarContent = withRouter((logout: AvatarContentProps) => {
  return (
    <div>
         // pass in history to callBack function
          <p style={{ margin: 0 }} onClick={() => removeToken(logout, props.history)} >
            <Icon type="logout" />
            Logout
        </p>
        </div>
      );
    })

   //give an additional argument to this function so it can take in history
    const removeToken = ({ logout }: AvatarContentProps, history) => {
      const cookies = new Cookies();
      if (cookies.get('token')) {
        cookies.remove('token')
        logout(AuthStatus.isNotLoggedIn)
        //make use of history object
        history.push("/login")
      } else {
        return null;
      }
    }