在 React 中添加身份验证以避免重新加载时重定向到主页的更好方法

时间:2021-07-13 06:28:12

标签: reactjs authentication react-redux react-router jwt

我正在我的 React 应用程序中添加 StudentTeacher 身份验证,我正在从后端获取 JWT 并将该令牌存储在 localstorage.

App.js

componentDidMount() {
    this.props.onTryLogin();
  }
render() {
const {teacherToken, studentToken} = this.props;
let routes = (
      <Switch>
        <Route
          path="/"
          exact
          component={<Homepage />}
        />
        <Redirect to="/" />
      </Switch>
    );

    if (teacherToken) { // if teacher is logged In
      routes = (
        <Fragment>
          <Switch>
            <Route
              path="/"
              exact
              component={<Homepage />}
            />

            <Route
              path="/teacher"
              component={<LMS />}
            />
          </Switch>
        </Fragment>
      );
    }
    if (studentToken) { // If student is logged in
      routes = (
        <Fragment>
          <Switch>
            <Route
              path="/"
              exact
              component={<Homepage />}
            />
            <Route
              path="/student"
              component={<LMS />}
            />
          </Switch>
        </Fragment>
      );
    }
  return (
      <BrowserRouter>
        <div>{routes}</div>
      </BrowserRouter>
  );
}
const mapStateToProps = (state) => {
  return {
    studentToken: state.auth.studentToken, // student token is stored in this state.
    teacherToken: state.auth.teacherToken, // teacher token is stored in this state.
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onTryLogin: () => {
      dispatch(actionCreators.authCheckState()); // checks if student/teacher is loggedIn and fetch the token from localstorage into the state.
    },
  };
};

但是在这种情况下,如果我以 Teacher 身份登录并且我在路径 /teacher/lecture/ 上,并且如果我刷新页面,我会被重定向到 /teacher/

现在我的问题是,如果我在路径 /teacher/lecture/ 上重新加载页面,它不会将我重定向到 /teacher/但让我走在同一条路上。

0 个答案:

没有答案