2017-10-10 837 views
1

我对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; 
} 

由于提前,如果你需要任何额外的代码片段只是请让我知道。

+0

中检索数据试图执行'localStorage.getItem('token')'并在应用程序挂载后立即登录用户?因为它本身不会发生。 –

+1

要清楚:刷新页面时,所有'state'都会丢失;任何你想保存的东西都必须手动保存和恢复。 –

回答

0

您需要在localStorage中保留应用程序状态。 Here是由Redux的创建者Dan Abramov所作的教程。

2

要通过页面刷新来保留Redux状态,您需要将应用程序状态存储在localStorage中,并在页面加载时检索它。尝试发送App组件的componentDidMount中的操作,该组件从localStorage

+0

或使用[redux-persist](https://github.com/rt2zz/redux-persist) – Dane