Tes*_*uji 5 javascript reactjs redux
存储用户登录数据(主要是用户名或 uuid)的最佳且安全的方法是什么。那么,我可以在其他组件中使用它吗?我想了几种方法来做到这一点。
我的 authLogin 方法:
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))
})
}
}
Run Code Online (Sandbox Code Playgroud)
我认为你的想法是正确的。像您正在做的那样对用户进行身份验证,将令牌存储在 localStorage 中,并将用户数据保存在 redux 中。由于刷新会导致 redux 存储重新启动,并且您仍然需要用户数据,因此我会在应用程序中的某个位置分派一个操作,可能是在应用程序首次安装时在应用程序的根目录周围,以根据保存的令牌获取登录的用户数据在本地存储中。
像这样的东西:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
至于通过路由器传递道具,您必须使用 renderProp,这可能有点棘手。您能分享一下您的路由器问题的代码吗?
| 归档时间: |
|
| 查看次数: |
6062 次 |
| 最近记录: |