如何使用React-Redux检查登录状态?

Daw*_*n17 3 javascript reactjs redux

我刚刚学会了react-redux工作原理。我目前已经登录,但是我不确定如何检查用户是否登录。

我用flask创建了一个后端,并axiosPOST请求的前面使用了它。

登录后,它只会为我提供成功状态。

现在,我想在全局上应用它,以便导航栏显示用户名并可以访问其自己的页面。

如何react-redux检查用户是否已登录?

需要采取什么行动,我该如何制定呢?

dev*_*kan 10

这取决于您的身份验证逻辑,但简单来说,您将创建一个用于登录的操作,然后根据该操作更改状态。例如,您可以在商店中具有身份验证状态,然后可以在其中保存用户和身份验证信息。成功登录后,Reducer处理状态更改。

无论何时需要登录信息,都可以通过auth状态进行检查,并根据此状态渲染组件。当然,这个组件需要连接到您的商店,或者从连接到商店的容器组件中获取一些道具。另外,如果您使用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());
  }
};
Run Code Online (Sandbox Code Playgroud)

减速器

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;
  }
};
Run Code Online (Sandbox Code Playgroud)

组件示例

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

您可以连接此组件以从容器存储或获取此身份验证道具。连接示例:

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

export default connect(mapStateToProps)(App);
Run Code Online (Sandbox Code Playgroud)