javascript - 如何使用 redux 保持用户登录状态?

标签 javascript reactjs authentication redux store

我正在开发一个具有用户身份验证的应用程序。现在,我的登录当前发生在 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
};

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

最佳答案

当 HoC 组件安装时,它总是也会安装 Nav 组件。

Nav 组件具有 this.props.getCurrentUser(); ,与 this.props.setCurrentUser() 相同。

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

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

getCurrentUserAction 在用户登录的情况下处理获取用户数据的请求,然后分派(dispatch) RECEIVE_USER 操作,该操作会更改 redux 状态(通过reducer)。

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

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

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

关于javascript - 如何使用 redux 保持用户登录状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57401401/

相关文章:

reactjs - ReactJs中按钮提交外部标签formik时如何提交Formik?

javascript - 更改输入文本时不会应用过滤器 : ReactJS

authentication - 如何从授权码中获取谷歌授权 token ?

javascript - 浏览器中Javascript源代码中的"w()"、"n()"

javascript - Chrome 中的 WebSQL 和 localStorage 范围

reactjs - 如何使用本地后端在本地运行生产 react 应用程序

Laravel 和 Passport 获取 SQLSTATE[42S22] : Column not found: 1054 Unknown column 'api_token'

php - 在 php 和 Ruby On Rails 应用程序之间传递身份验证

javascript - Bootstrap进度条动画不起作用

javascript - 选择列Jquery下的所有行