我對React和Redux真的很陌生,我一直在關注Stephen Grider的Advanced React和Redux課程,並且我正在進行身份驗證的客戶端。我已經有一個令牌保存在我的本地存儲中,並且一切似乎都正常,直到我刷新頁面。當我登錄/註冊導航更改以顯示註銷按鈕時,但如果手動刷新頁面,導航會變回顯示登錄/註冊按鈕。React-Redux狀態在刷新後丟失了
我真的很陌生,不知道我應該包含哪些代碼片段。我將離開reducer和actions/index.js。另外this是我的git存儲庫的一個例子。
動作/ 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 };
}
減速/ 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;
}
由於提前,如果你需要任何額外的代碼片段只是請讓我知道。
中檢索數據試圖執行'localStorage.getItem('token')'並在應用程序掛載後立即登錄用戶?因爲它本身不會發生。 –
要清楚:刷新頁面時,所有'state'都會丟失;任何你想保存的東西都必須手動保存和恢復。 –