adn*_*n98 0 javascript authentication reactjs redux
如标题所示 - 当我在 React/Redux 应用程序中重新加载页面时,用户正在注销。我将令牌存储在 localStorage 中,但它不起作用,因此可能有任何错误。用户登录时应存储令牌。注销工作正常。这是我的代码:
auth.js(reducers 目录 - Redux):
import { LOGIN_SUCCESS, LOGIN_FAIL, LOGOUT_SUCCESS, REGISTER_SUCCESS, REGISTER_FAIL } from '../actions/types';
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: null,
isLoading: false,
isRegistered: false
}
export default function(state = initialState, action) {
switch(action.type) {
case REGISTER_SUCCESS:
return {
...state,
...action.payload,
token: null,
isAuthenticated: false,
isLoading: false,
isRegistered: true
}
case LOGIN_SUCCESS:
localStorage.setItem('token', action.payload.token);
return {
...state,
...action.payload,
isAuthenticated: true,
isLoading: false,
}
case LOGIN_FAIL:
case LOGOUT_SUCCESS:
case REGISTER_FAIL:
localStorage.removeItem('token');
return {
...state,
token: null,
isAuthenticated: false,
isLoading: false
}
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我真的不知道您如何检查是否有登录用户,但是当您刷新页面时,商店不会自动填充。因此,如果您检查身份验证状态,也许您应该添加类似的内容isAuthenticated:
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: localStorage.getItem('token') ? true : false, // or just !!localStorage.getItem('token')
isLoading: false,
isRegistered: false
}
Run Code Online (Sandbox Code Playgroud)
或者使用一些函数来检查 localStorage 并相应地更新商店。
| 归档时间: |
|
| 查看次数: |
3425 次 |
| 最近记录: |