React路由中如何修改this.props.location.state并传递给目标组件
你描述的登录后回跳需求完全可以通过路由state传递参数实现,具体实现流程如下:
1 受保护路由重定向时注入state参数
在路由拦截逻辑中,当检测到用户未登录需要跳转到登录页时,将用户当前要访问的页面地址存入重定向配置的state字段中:
// 受保护路由封装示例(基于react-router v5) import { Route, Redirect } from 'react-router-dom'; const ProtectedRoute = ({ component: Component, isAuthenticated, ...rest }) => ( <Route {...rest} render={props => isAuthenticated ? ( <Component {...props} /> ) : ( // 重定向到登录页时,把当前请求的地址存入state.from <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> ) } /> )
2 登录页获取state参数完成回跳
类组件需要先通过withRouter高阶组件包裹,才能拿到路由相关的location、history属性,登录成功后读取state参数跳转即可:
// 类组件登录页示例 import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; class Login extends Component { // 登录请求成功后的回调逻辑 handleLoginSuccess = async () => { // 调用登录接口逻辑省略 await loginApi(userInfo); const { state } = this.props.location; // 存在跳转来源则跳回原页面,否则默认跳转到控制台首页 const targetPath = state?.from?.pathname || '/dashboards/index'; // 用路由提供的history方法跳转,不要直接修改window.location避免整页刷新 this.props.history.push(targetPath); } render() { // 登录表单渲染逻辑省略 } } export default withRouter(Login);
注意事项
this.props.location.state是只读属性,不要直接修改它的值,传递自定义参数需要在调用history.push/history.replace或者使用<Redirect>组件时,在to配置的state字段中传入自定义数据。- 直接修改
window.location会触发浏览器整页刷新,丢失React应用的内存状态,优先使用路由提供的history方法完成跳转。 - 若用户直接访问登录页,没有从受保护页面跳转而来,
this.props.location.state会为undefined,需要做好兜底跳转逻辑避免报错。
内容的提问来源于stack exchange,提问作者mo akh
相关产品推荐
相关产品推荐

