我正在我的 React 应用程序中添加 Student 和 Teacher 身份验证,我正在从后端获取 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/但让我走在同一条路上。