簡體   English   中英

如何使用React-Redux檢查登錄狀態?

[英]How to check login status with React-Redux?

react-reduxreact-redux工作原理。 我目前有登錄,但我不知道如何檢查用戶是否已登錄。

我創建了一個后端與燒瓶和使用axios在主音到POST請求。

登錄后,它只是給我一個成功的狀態。

現在我想全局應用它,以便導航欄顯示用戶名並可以訪問自己的頁面。

如何使用react-redux檢查用戶是否已登錄?

需要采取什么樣的行動?我該如何制作它?

這取決於您的身份驗證邏輯,但只是,您將創建一個登錄操作,然后根據此操作更改您的狀態。 例如,您可以在商店中擁有身份驗證狀態,然后您可以在那里保存用戶和身份驗證信息。 成功登錄后,您的reducer將處理狀態更改。

無論您需要登錄信息,都可以通過身份驗證狀態進行檢查,並根據此情況呈現您的組件。 當然,要么將此組件連接到您的商店,要么從連接到商店的容器組件獲取一些道具。 此外,如果您使用React Router,您可以根據您的身份驗證狀態擁有公共或私人路由。

我在這里有一個示例沙盒: https//codesandbox.io/s/yk519xy7px

以下是我的示例中針對此邏輯的一個非常簡單的代碼片段:

行動創造者

const userLogin = username => ({
  type: types.AUTH_LOGIN,
  username,
});

// mimicking an async API login endpoing
const fakeLoginRequest = username =>
  new Promise((resolve, reject) =>
    setTimeout(() => {
      username === "foo" ? resolve(username) : reject("No such user");
    }, 1000),
  );

// handling async login 
export const doLogin = username => async dispatch => {
  // incrementProgress is responsible for progress status.
  // Firing a spinner while fetching login info.
  dispatch(incrementProgress());
  try {
    const userResponse = await fakeLoginRequest(username);
    dispatch(userLogin(userResponse));
    // if successfull change our route to "dashboard"
    history.push("/dashboard");
  } catch (error) {
    handleError(error);
  } finally {
    dispatch(decrementProgress());
  }
};

減速器

const initialState = {
  username: "",
  isLoggedIn: false
};

const authReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.AUTH_LOGIN:
      return {
        ...state,
        username: action.username,
        isLoggedIn: true
      };
    case types.AUTH_LOGOUT:
      return initialState;
    default:
      return state;
  }
};

示例組件部分

 render() {
    const { auth } = this.props;
    return (
        auth ? <div>Logged in</div> : <div>Not logged in</div>
    )
  }

您可以連接此組件以存儲或從容器中獲取此auth prop。 連接示例:

const mapStateToProps = state => ({
  auth: state.auth
});

export default connect(mapStateToProps)(App);

好吧,你應該創建一個具有某種初始狀態的reducer,可能是類似的

const initialLoginState = {
  userInformation: null,
};

export default function login(state = initialLoginState, action) {
  switch (action.type) {
    case 'SET_USER_INFORMATION':
      return { ...state, userInformation: action.userInfo };
  }

  return state;
}

與相應的行動

export const setUserInformation = (userInfo) => ({
  userInfo,
  type: 'SET_USER_INFORMATION',
});

然后,當您在成功登錄后從后端接收用戶信息時,您將調度setUserInformation以將數據存儲在Redux中。 然后,您可以通過Store.getState().login.userInformation從任何地方訪問它(假設您已通過combineReducers等將login reducer添加到您的商店)。

此外,我將研究如何在有興趣訪問該值的組件中使用connect HOC。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM