我为我的应用实现了一个简单的身份验证层,每次用户会话过期时,我都会收到此错误消息,而不是在首页上重定向。
redux / actions / authentication.js :
import axios from 'axios';
import { GET_ERRORS, SET_CURRENT_USER } from './types'; // we list here the actions we'll use
import setAuthToken from '../../setAuthToken';
import jwt_decode from 'jwt-decode';
export const registerUser = (user, history) => dispatch => {
axios.post('/api/users/register', user)
.then(res => history.push('/login'))
.catch(err => {
dispatch({
type: GET_ERRORS,
payload: err.response.data
});
});
}
export const loginUser = (user) => dispatch => {
axios.post('/api/users/login', user)
.then(res => {
//console.log(res.data);
const { token } = res.data;
localStorage.setItem('jwtToken', token);
setAuthToken(token);
const decoded = jwt_decode(token);
dispatch(setCurrentUser(decoded));
})
.catch(err => {
dispatch({
type: GET_ERRORS,
payload: err.response.data
});
});
}
export const setCurrentUser = decoded => {
return {
type: SET_CURRENT_USER,
payload: decoded
}
}
export const logoutUser = (history) => dispatch => {
localStorage.removeItem('jwtToken');
setAuthToken(false);
dispatch(setCurrentUser({}));
history.push('/login');
}
src / App.js (相关部分):
if(localStorage.jwtToken) {
setAuthToken(localStorage.jwtToken);
const decoded = jwt_decode(localStorage.jwtToken);
store.dispatch(setCurrentUser(decoded));
const currentTime = Date.now() / 1000;
if(decoded.exp < currentTime) {
store.dispatch(logoutUser());
window.location.href = '/login'
}
}
/login
页面存在。出现此错误时-我可以刷新页面,应用程序将在/
上重定向我。为什么会这样?
答案 0 :(得分:1)
在商店中注册logoutUser时必须传递历史对象。
if(decoded.exp < currentTime) {
store.dispatch(logoutUser(history));
window.location.href = '/login'
}
否则它将是不确定的
答案 1 :(得分:0)
如果历史记录处于您的状态,则可以使用getState()将其拉回。如果它不在getState中,则如上所述,您必须将该值传递到logoutUser调用中。
if(localStorage.jwtToken) {
setAuthToken(localStorage.jwtToken);
const decoded = jwt_decode(localStorage.jwtToken);
store.dispatch(setCurrentUser(decoded));
const currentTime = Date.now() / 1000;
if(decoded.exp < currentTime) {
store.dispatch(logoutUser());
window.location.href = '/login'
}
}
export const logoutUser = () => (dispatch, getState) => {
localStorage.removeItem('jwtToken');
setAuthToken(false);
dispatch(setCurrentUser({}));
getState().user.history.push('/login'); //replace user with wherever your history is within your state
}