You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-router-dom@4.3.1:Hook实现页面导航、返回及传参方案求助

react-router-dom@4.3.1 实现页面跳转、返回及传参方案

react-router-dom@4.x版本没有内置useHistory或useNavigate这类路由Hook,要实现无Link组件的页面跳转、返回,核心是通过withRouter高阶组件注入路由对象,或者自定义Hook封装路由上下文来实现。

一、用withRouter获取history对象实现跳转/返回

withRouter会把路由相关的history、location、match对象注入到组件props中,直接用history.push做跳转,history.goBack做返回。

示例组件:跳转+返回操作

import React from 'react';
import { withRouter } from 'react-router-dom';

const PageController = ({ history }) => {
  // 跳转页面并传递数据
  const goToTarget = () => {
    // 方式1:通过state传参(页面刷新后数据会丢失)
    history.push('/target', { username: 'shabnam', userId: 1001 });
    
    // 方式2:通过URL参数传参(刷新后数据保留)
    // history.push({
    //   pathname: '/target',
    //   search: '?username=shabnam&userId=1001'
    // });
  };

  // 返回上一页
  const goBackPage = () => {
    history.goBack();
    // 如需返回多页,用history.go(-2)表示返回2页
  };

  return (
    <div>
      <button onClick={goToTarget}>跳转到目标页</button>
      <button onClick={goBackPage}>返回上一页</button>
    </div>
  );
};

// 必须用withRouter包装组件才能拿到路由对象
export default withRouter(PageController);

二、目标页面接收传递的数据

根据传参方式不同,接收逻辑也有区别:

1. 接收state参数

同样用withRouter包装目标组件,从location.state中读取数据:

import React from 'react';
import { withRouter } from 'react-router-dom';

const TargetPage = ({ location }) => {
  // 加|| {}避免state为undefined时报错
  const { username, userId } = location.state || {};

  return (
    <div>
      <p>用户名:{username}</p>
      <p>用户ID:{userId}</p>
    </div>
  );
};

export default withRouter(TargetPage);

2. 接收URL参数

用URLSearchParams解析URL中的search参数,或者如果路由配置了动态参数,直接从match.params读取:

import React from 'react';
import { withRouter } from 'react-router-dom';

const TargetPage = ({ location }) => {
  const searchParams = new URLSearchParams(location.search);
  const username = searchParams.get('username');
  const userId = searchParams.get('userId');

  return (
    <div>
      <p>用户名:{username}</p>
      <p>用户ID:{userId}</p>
    </div>
  );
};

export default withRouter(TargetPage);

三、自定义Hook封装(简化重复操作)

如果不想每次都用withRouter包装组件,可以自己封装一个useHistory Hook,利用react-router的上下文获取路由对象:

import React from 'react';
import { RouterContext } from 'react-router-dom';

const useHistory = () => {
  const routerContext = React.useContext(RouterContext);
  if (!routerContext) {
    throw new Error('useHistory必须在Router组件内部使用');
  }
  return routerContext.history;
};

// 使用示例
const MyComponent = () => {
  const history = useHistory();
  
  const handleJump = () => {
    history.push('/target', { info: '自定义Hook传参' });
  };

  return <button onClick={handleJump}>跳转</button>;
};

内容的提问来源于stack exchange,提问作者shabnam lashkary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:30:32