如何解决登录后反应重定向
我在React应用程序中有ajax登录。它处理LoginForm组件。乘法也使用React router 登录ajax之后,我想做一些类似重定向到另一个React页面的操作。成功登录后,我不知道如何正确地从登录页面重定向到首页。有人可以帮我吗?我正在使用类样式来制作组件。
这是LoginForm组件中的代码:
sendData(e)
{
e.preventDefault();
this.setState({'errors': [],'success': []});
let formData = new FormData();
formData.set('name',this.state.name);
formData.set('password',this.state.password);
axios({
method: 'POST',//url: 'http://localhost:8000/login'
data: formData,headers: {
'Content-Type': 'text/html','X-Requested-With': 'XMLHttpRequest',}
})
.then(response => {
// Here should be the redirect to another React page
})
.catch(response => {
this.setState({errors: ['Login fails. Try it again later please.']})
});
}
反应路由器看起来像
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<NavLink to="/" className="nav-link">Home</NavLink>
</li>
<li className="nav-item">
<NavLink to="/login" className="nav-link">Login</NavLink>
</li>
<li className="nav-item">
<NavLink to="/about" className="nav-link">About</NavLink>
</li>
</ul>
</div>
<div className="container-fluid">
<div>
<Switch>
<Route path="/" exact>
<Home />
</Route>
<Route path="/login">
<Login />
</Route>
<Route path="/about" component={About}/>
</Switch>
</div>
</div>
解决方法
如果您正在使用功能组件,则可以使用useHistory
提供的use react-router-dom
挂钩。
成功登录后,重定向到主页,如下所示:
import { useHistory } from 'react-router-dom';
const Login = () => {
const routerHistory = useHistory();
...
const sendData = (e) => {
...
.then(response => {
// Here should be the redirect to another React page
routerHistory.push('/');
})
...
}
...
}
您还可以使用history
道具,它是从React Router传递过来的道具之一。这同样适用于基于类的组件。
class Login {
...
sendData(e) {
...
.then(response => {
// Here should be the redirect to another React page
this.props.history.push('/');
})
...
}
...
}
如果由于您应用中组件的层次结构而没有传递Login
组件到路由器道具,那么您可以使用withRouter
高阶组件来访问history
对象。 / p>
import { withRouter } from "react-router";
class Login {
...
}
export default withRouter(Login);
有关详细信息,请参见:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。