如何使用react-router-dom无需触发事件跳转,实现登录成功后打开首页
登录成功后跳转首页实现方案
根据你当前使用的技术栈,可选择对应方案实现跳转:
- 纯浏览器原生跳转(无前端路由框架场景)
登录场景更推荐使用replace方法,登录成功后点击浏览器后退不会回到登录页:
window.location.replace('/') // 如果需要保留登录页历史记录,可使用以下代码: // window.location.href = '/'
如果你的首页路由不是根路径/,替换成实际的首页地址即可,比如/home、/dashboard。
- 使用React Router v6 路由场景
首先在登录组件顶部引入useNavigate钩子:
import { useNavigate } from 'react-router-dom'
在组件内部调用钩子拿到跳转方法即可使用:
const LoginComponent = (props) => { const navigate = useNavigate() // 其他组件逻辑保持不变 const sendData = (e) => { e.preventDefault(); axios({ method: "POST", url: url, data: data, headers: header }) .then((res) => { if (res.data.status === "success") { props.sethistory(res.data.data.user.history); props.setsignedIn(true); // 新增跳转代码 navigate('/') } }) .catch((err) => console.log(err)); }; }
- 使用React Router v5 路由场景
首先在登录组件顶部引入useHistory钩子:
import { useHistory } from 'react-router-dom'
在组件内部调用钩子拿到跳转方法即可使用:
const LoginComponent = (props) => { const history = useHistory() // 其他组件逻辑保持不变 const sendData = (e) => { e.preventDefault(); axios({ method: "POST", url: url, data: data, headers: header }) .then((res) => { if (res.data.status === "success") { props.sethistory(res.data.data.user.history); props.setsignedIn(true); // 新增跳转代码 history.push('/') } }) .catch((err) => console.log(err)); }; }
内容的提问来源于stack exchange,提问作者Ashutosh Saini
相关产品推荐
相关产品推荐

