Javascript 如何使用React/Redux获取登录用户的用户名(或任何其他数据)
存储用户登录数据(主要是用户名或uuid)的最佳安全方式是什么。那么,我可以在我的其他组件中使用它?我想了几种方法来做这件事Javascript 如何使用React/Redux获取登录用户的用户名(或任何其他数据),javascript,reactjs,redux,Javascript,Reactjs,Redux,存储用户登录数据(主要是用户名或uuid)的最佳安全方式是什么。那么,我可以在我的其他组件中使用它?我想了几种方法来做这件事 登录/注册后,将用户名存储在本地存储中,并在authsession结束时将其删除。(非常容易实施,但最不安全的可能) 通过AuthLogin/AuthSignup方法传递电子邮件,但我似乎不知道如何通过路由器传递。我还注意到,如果浏览器被刷新,即使用户仍然登录,这也不起作用 Cookie(还不知道如何与react一起使用) 我的authLogin方法: export c
export const authLogin = (email, password) => {
return dispatch =>{
dispatch(authStart());
axios.post('http://127.0.0.1:8000/rest-auth/login/',{
email: email,
password: password,
})
.then(res => {
const token = res.data.key;
const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
localStorage.setItem('token',token);
localStorage.setItem('expirationDate',expirationDate)
localStorage.setItem('email', email)#method 1
console.log("My token",localStorage.getItem('token'))
dispatch(authSuccess(token,email));#method 2
dispatch(checkAuthTimeout(3600));
})
.catch(err => {
dispatch(authFail(err))
})
}
}
我认为你的想法是对的。在执行操作时对用户进行身份验证,将令牌存储在localStorage中,并将用户数据保存在redux中。由于刷新会导致redux存储重新启动,并且您仍然需要您的用户数据,因此我会在应用程序中的某个位置发送一个操作,可能是在应用程序首次装载时,在应用程序的根目录附近,根据保存在localStorage中的令牌获取登录的用户数据 大概是这样的:
class App extends Component {
componentDidMount() {
// User will come from the store. If we do not have a user,
// but we have a token, then the user is logged in
if (!this.props.user && sessionStorage.getItem('token')) {
// a redux dispatch function to authenticate a JWT
this.props.validateJWT();
}
}
}
至于通过路由器传递道具,你必须使用渲染器,这可能有点棘手。你能分享你关于路由器问题的代码吗?这主要是基于观点的,但我总是通过第一种方法来完成。进行身份验证,然后将访问令牌存储在本地存储或会话存储中。我明白了。非常感谢。第一种方法似乎“太简单了”,所以我认为它是不正确的。