2017-10-10 19 views
1

私はReactとReduxの新機能です。私はStephen GriderのAdvanced ReactとReduxコースに従っています。私はすでにローカルストレージにトークンを保存しており、ページをリフレッシュするまですべてが正常に動作しているようです。サインイン/サインアップすると、ナビゲーションが変更されてログアウトボタンが表示されますが、手動でページを更新するとナビゲーションが元に戻り、サインイン/サインアップボタンが表示されます。リフレッシュ後にReact-Redux状態が失われました

私は本当にこれが新しく、コードスニペットとしてどのように含めるべきか分かりません。私は減速機とアクション/ 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

クリアするには:ページを更新するとすべての状態が失われます。保存したいものは手動で保存して復元する必要があります。 –

答えて

0

localStorageにアプリ状態を維持する必要があります。 Hereはreduxの作成者Dan Abramovが作成したチュートリアルです。

2

ページリフレッシュでRedux状態を保持するには、localStorageにアプリステータスを保存して、ページの読み込み時に取得する必要があります。 localStorage

+0

を使用するか、[redux-persist](https://github.com/rt2zz/redux-persist) – Dane

関連する問題