在尝试成功登录后将用户重定向到主页时,我遇到了问题。我正在github中使用此示例。
https://github.com/cornflourblue/react-redux-registration-login-example
在此文件“ src / LoginPage / LoginPage.jsx”中,有一个这样的部分可以在POST消息中发送登录请求,但是我看不到任何重定向到首页的信息,只是登录页面。这是一部分:
handleSubmit(e) {
e.preventDefault();
this.setState({ submitted: true });
const { username, password } = this.state;
const { dispatch } = this.props;
if (username && password) {
dispatch(userActions.login(username, password));
}
}
当我查看网络活动时,看到从服务器的响应中收到成功的消息。我需要添加一些可以重定向的内容吗?
答案 0 :(得分:0)
是的,您需要向项目中添加Browser Routing
,成功登录后,您应该重定向到所需的页面。例如to="/Home"
。首先,在redux reducer中需要类似isAuth
的东西。登录提交后,如果成功,则将其设置为true,并在您的LoginPage
中用mapStateToProps
获取此isAuth
值。同样,在您的render()
部分中,请在其他jsx
代码->
render() {
let redirect = null;
if(isAuth == true){
redirect = <Redirect to="/Home" />;
}
return (
{redirect}
)
}
答案 1 :(得分:0)
我找到了问题的原因。如果响应成功,则必须在localStorage中设置一些内容。在专用路由中,它将检查localStorage中是否存在该对象。如果没有,它什么也不会做,但是如果有,它将操作要重定向的组件。我忘了编辑这部分。因此,它没有进行重定向。