首页 > 解决方案 > 如何保持用户使用 redux 登录?

问题描述

我正在开发具有用户身份验证的应用程序。现在,我的登录当前是在 withAuth HOC 中进行的,而我的 Nav 组件已设置为获取当前用户。

然而,虽然用户可以登录并访问他们的个人资料页面,但一旦他们离开个人资料,当前用户就是空的。

如何设置我的商店和/或组件,以便当前用户在每个页面上都可用。

我试图将用户传递给我的导航组件,但是一旦您离开个人资料,就根本没有用户

这是我的 withAuth HOC:


export default function withAuth(WrappedComponent) {

  class Something extends React.Component {

    componentDidMount() { 

  **//checks if user is logged in before loading to the WrappedComponent (which in this case is the profile page)**

      if (!localStorage.token) {
        this.props.history.push("/login")
      }
      try {
        this.props.getCurrentUser()
        .catch(error => {
          this.props.history.push("/login")
        })
      } catch (error) {
        if (error.message === "Please log in") {
          this.props.history.push("/login")
        }
      }
      }

      render() {

        return (

<WrappedComponent />

      )}
    }

    const mapDispatchToProps = {
      getCurrentUser: getCurrentUserAction

**//does a fetch to 'http://localhost:3000/profile' with the bearer token and returns the username**

    }

    return withRouter(connect(null, mapDispatchToProps)(Something))
}

这是我的导航组件(导入到每个页面):


  componentDidMount() {
    this.props.getCurrentUser();

**//This should fetch from 'http://localhost:3000/profile' with the bearer token and return the username**

  }
...
const mapStateToProps = state => {
  return {
    user: state.user
  };
};

const mapDispatchToProps = {
  getCurrentUser: getCurrentUserAction,
  logout: userLogoutAction
};

我明白为什么用户在个人资料中可见,但不明白为什么它在其他任何地方都不可见

标签: javascriptreactjsauthenticationreduxstore

解决方案


当 HoC 组件挂载时,它也总是挂载 Nav 组件。

Nav 组件具有this.props.getCurrentUser();this.props.setCurrentUser().

我敢打赌,您有一些将用户重定向回登录的竞争条件。

我建议您重构代码并正确使用 redux,在这种情况下可能是

getCurrentUserAction如果用户登录,则处理获取用户数据的请求,然后调度RECEIVE_USER操作,这会更改 redux 状态(通过 reducer)。

HoC 确保用户已登录并在必要时分派操作。

Nav 组件使用选择器来获取它需要的用户数据(因为 HoC 在这里充当守卫)。

以上可能不是您的最佳解决方案,但它可以解决您的问题。


推荐阅读