Redux store changes when reload page

2019-07-20 15:58发布

问题:

I am implementing login with two different type of users using react redux. This is my login method:

export const login = (credentials) => (dispatch) =>
    api.user.login(credentials).then(user => {
      localStorage.userJWT = user.token;
      localStorage.userEmail = user.email;
      localStorage.userId = user.id;
      localStorage.surname = user.surname;
      localStorage.type = user.type;
      dispatch(userLoggedIn(user));
});
  1. For the first type of user, I return from backend: token, email, id, surname.
  2. For the second type of user, I return from backend: token, email, id, type.

I do some secured routes which the second type of user cannot access. So if the variable surname is returned, I define the specific route for that user.

If type variable is returned, it shows properly everything in links and in redux store as well. However, if I reload the page, then it automatically changes variable type into undefined surname.

This is where I am trying to save the redux state in store even if I reload the page. const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) );

 if(localStorage.userJWT && localStorage.userEmail && localStorage.userId && localStorage.type){
   const user = { token: localStorage.userJWT, email: localStorage.userEmail, id: localStorage.userId, type: localStorage.type};
   store.dispatch(userLoggedIn(user));
 }
 if(localStorage.userJWT && localStorage.userEmail && localStorage.userId && localStorage.surname){
   const user = { token: localStorage.userJWT, email: localStorage.userEmail, id: localStorage.userId, surname: localStorage.surname};
   store.dispatch(userLoggedIn(user));
 }

Can you please suggest why it is not following my if statement. Thank you in advance.

回答1:

The Redux store/state is re-initialized on reload. You can keep your auth info in local storage, then pull that out to use as your initial state. That way, your Redux state will always have that auth information, even on reload.

function reducer (state = initState(), action) {
    return state
}

function initState () {
    return { 
        token: localStorage.userJWT, 
        email: localStorage.userEmail, 
        id: localStorage.userId, 
        surname: localStorage.surname
    }
}

Or, if you want to keep your entire Redux state on reload, you can try to implement some package that does that, like redux-persist.