javascript - 如何保持用户使用 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
};
我明白为什么用户在个人资料中可见,但不明白为什么它在其他任何地方都不可见
解决方案
当 HoC 组件挂载时,它也总是挂载 Nav 组件。
Nav 组件具有this.props.getCurrentUser();
与this.props.setCurrentUser()
.
我敢打赌,您有一些将用户重定向回登录的竞争条件。
我建议您重构代码并正确使用 redux,在这种情况下可能是:
getCurrentUserAction
如果用户登录,则处理获取用户数据的请求,然后调度RECEIVE_USER
操作,这会更改 redux 状态(通过 reducer)。
HoC 确保用户已登录并在必要时分派操作。
Nav 组件只使用选择器来获取它需要的用户数据(因为 HoC 在这里充当守卫)。
以上可能不是您的最佳解决方案,但它可以解决您的问题。
推荐阅读
- python - 在python中使用public_key进行KeyCloak解码
- mysql - 如何删除在 2 个表中找到的常见记录?
- c# - 如何在.net核心中使用自动映射器保存目标值
- javascript - 打字稿和 javascript 混合项目的更漂亮的自动格式化错误
- angular - 无法使用 ngx-doc-viewer 构建 Angular 项目
- html - data-option-value 属性有什么作用?
- java - 有人可以帮我处理返回功能吗?
- c++ - 打印所选长度字符的所有排列并在 CPP 中重复
- java - Java DeleteMapping 方法不允许
- ssh - 从 gpg 子密钥中导出不同的 ssh 密钥