用户成功登录后,必须将用户重定向到另一个页面。如果您尚未登录,则无法访问该页面。
这是登录表单代码
class LoginForm extends React.Component {
handleFormSubmit = e => {
e.preventDefault();
const user = e.target.elements.user.value;
const password = e.target.elements.password.value;
this.props.onAuth(user, password);
};
componentDidUpdate() {
console.log(this.props.successLogin)
};
这是mapStateToProps和mapDispatchToProps函数
const mapStateToProps = (state) => {
return {
error: state.error,
successLogin: state.token
}
};
mapDispatchToProps = dispatch => {
return {
onAuth: (username, password) => dispatch(actions.authLogin(username, password))
}
};
这是它的动作
export const authSuccess = token => {
return {
type: actionTypes.AUTH_SUCCESS,
token: token
}
};
这是登录页面中的代码
const PrivateRoute = ({component: Component, ...rest}) => (
<Route {...rest} render={(props) => (
rest.auth
? <Component {...props}/>
:
<Redirect to='/'/>
)}/>
);
这是路由链接
<PrivateRoute path="/Main_Page" exact component={Main_Page} auth={this.props.isAuthenticated}/>
及其连接
const mapStateToProps = state => {
return {
isAuthenticated: state.token !== null
};
};
console.log打印两次。 空和带有实际令牌的那些。
我的问题是,在使console.log(this.props.successLogin)
打印的内容为null且使令牌无效,而注销时又为null的逻辑中有什么问题?
这带来的挑战是我的页面最终被重定向到<Redirect to='/'/>``, although I am authenticated, and I can access all the
PrivateRoute路径`
答案 0 :(得分:0)
您将必须检查用户是否已成功通过身份验证,或者在渲染之前也必须检查
{this.props.isAuthenticated && <PrivateRoute path="/Main_Page" exact component={Main_Page} auth={this.props.isAuthenticated}/>}
答案 1 :(得分:0)
这是我修复的方式
<Route exact path="/"render={() => (this.props.isAuthenticated ? (
<Redirect to="/Main_Page"/>) : (
<Log_in_Page/>