【发布时间】:2018-03-22 05:49:08
【问题描述】:
我真的是 React 和 Redux 的新手,我一直在学习 Stephen Grider 的高级 React 和 Redux 课程,并且我正在做客户端的身份验证。我已经在本地存储中保存了一个令牌,并且在我刷新页面之前一切似乎都运行良好。当我登录/注册时,导航更改为显示注销按钮,但如果我手动刷新页面,导航更改回显示登录/注册按钮。
我对此真的很陌生,不知道我应该在代码 sn-ps 中包含什么。我将留下 reducer 和 actions/index.js。 this 也是我的 git 存储库的一个赞。
actions/index.js
import axios from 'axios';
import { browserHistory } from 'react-router';
import { push } from 'react-router-redux';
import { AUTH_USER, UNAUTH_USER, AUTH_ERROR } from './types';
const API_URL = 'http://localhost:3000';
export function signinUser({ username, password }) {
return function(dispatch) {
// Submit username/password to the server
axios
.post(`${API_URL}/signin`, { username, password })
.then(response => {
// If request is good...
// - Update state o indicate user is authenticated
dispatch({ type: AUTH_USER });
// - Save the JWT token to local storage
localStorage.setItem('token', response.data.token);
// - Redirect to the route '/feature'
browserHistory.push('/feature');
})
.catch(() => {
// If request is bad...
// -Show an error to the user
dispatch(authError('Bad login info'));
});
};
}
export function signupUser({ username, email, password }) {
return function(dispatch) {
axios
.post(`${API_URL}/signup`, { username, email, password })
.then(response => {
dispatch({ type: AUTH_USER });
localStorage.setItem('token', response.data.token);
browserHistory.push('/feature');
})
.catch(response => {
// TODO
console.log(response);
dispatch(authError('There was an error'));
});
};
}
export function authError(error) {
return {
type: AUTH_ERROR,
payload: error
};
}
export function signoutUser() {
localStorage.removeItem('token');
return { type: UNAUTH_USER };
}
reducer/auth_reducer.js
import { AUTH_USER, UNAUTH_USER, AUTH_ERROR } from '../actions/types';
export default function(state = {}, action) {
switch (action.type) {
case AUTH_USER:
return { ...state, error: '', authenticated: true };
case UNAUTH_USER:
return { ...state, authenticated: false };
case AUTH_ERROR:
return { ...state, error: action.payload };
}
return state;
}
提前致谢,如果您需要任何额外的代码 sn-p 请告诉我。
【问题讨论】:
-
您是否正在尝试执行
localStorage.getItem('token')并在应用安装后立即登录用户?因为它不会自行发生。 -
要明确:刷新页面时所有
state都会丢失;您想要保存的任何内容都必须手动保存和恢复。
标签: javascript reactjs redux