1.登入-React部分

React (in redux)登入部分的處理

首先是reducer:

export default function user(state={
  isWaiting: false,
  authenticated: false,
  error: null,
  favoriteRecipes: null }, action={}) {
  switch (action.type) {

    case MANUAL_LOGIN_USER:
      return Object.assign({}, state, {
        isWaiting: true
      });
    case LOGIN_SUCCESS_USER:
      return Object.assign({}, state, {
        isWaiting: false,
        authenticated: true,
        user: action.user
      });
    case LOGIN_ERROR_USER:
      return Object.assign({}, state, {
        isWaiting: false,
        authenticated: false
      });

    default:
      return state;
  }
}

登入成功表示authenticated = true,也會有user資料 失敗當然就什麼都沒有。

action部份:

export function manualLogin(data) {
  return dispatch => {
    dispatch({
      type: types.MANUAL_LOGIN_USER
    });

    return fetchHelper('post', '/api/login', data)
      .then((result) => {
        dispatch(loginSuccess(result));
      }).catch(() => {
        dispatch({
          type: types.LOGIN_ERROR_USER
        });
      });
  };
}
function loginSuccess(obj) {
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
    localStorage.setItem('token', obj.token);
  }
  return {
    type: types.LOGIN_SUCCESS_USER,
    user: obj.user
  };
}

這部分我是用Redux Thunk來做的, 其中loginSuccess裡面,將取到的token和user存在localStorage,關掉頁面再打開還是可以保留狀態。

所以在頁面一進來時要做狀態的檢查,如果在localStorage有token值要拿去登入。

export function checkLoginStatus(token) {
  if ((typeof localStorage !== 'undefined' && localStorage !== null)) {
    if (localStorage.getItem('token')) {
      return dispatch => {
        dispatch({
          type: types.MANUAL_LOGIN_USER
        });
        return fetchHelper('get', '/api/self', {
            token: localStorage.getItem('token')
          })
          .then((result) => {
            dispatch(loginSuccess({
              token: localStorage.getItem('token'),
              user: result
            }));
          }).catch(() => {
            dispatch({
              type: types.LOGIN_ERROR_USER
            });
          });
      };
    }
  }

  return {
    type: types.LOGOUT_SUCCESS_USER
  };
}

這樣大致上就完成登入的作業了。