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

React Router V6类组件中如何获取URL参数?

React Router V6类组件获取URL查询参数的解决方案

你遇到的问题包含两个关键点:一是原代码中this.window.location写法错误(window是全局对象,无需通过this访问);二是React Router V6移除了V5内置的withRouter高阶组件,类组件无法直接获取路由相关props。以下是两种可行的解决方法:

方法一:自定义withRouter高阶组件

React Router V6虽然移除了内置的withRouter,但可以自行实现一个,将路由相关的location、navigate等属性注入类组件:

  1. 创建withRouter.js文件:
import { useLocation, useNavigate, useParams } from 'react-router-dom';

export const withRouter = (Component) => {
  const Wrapper = (props) => {
    const location = useLocation();
    const navigate = useNavigate();
    const params = useParams();
    return <Component {...props} location={location} navigate={navigate} params={params} />;
  };
  return Wrapper;
};
  1. 修改BookingSummary类组件:
import React from 'react';
import { withRouter } from './withRouter';
import queryString from 'query-string';

class BookingSummary extends React.Component {
  componentDidMount() {
    // 通过props获取路由location对象的search部分
    const { search } = this.props.location;
    const movieInfo = queryString.parse(search);
    console.log('电影信息:', movieInfo);
  }

  render() {
    return <div>预订汇总页面</div>;
  }
}

// 用自定义的withRouter包裹组件
export default withRouter(BookingSummary);

方法二:用函数组件作为中间层传递参数

如果不想自定义HOC,可以写一个函数组件作为包裹层,使用React Router V6的useSearchParams钩子获取查询参数,再传递给类组件:

  1. 修改BookingSummary.js:
import React from 'react';
import { useSearchParams } from 'react-router-dom';

// 函数组件包裹层
const BookingSummaryWrapper = () => {
  const [searchParams] = useSearchParams();
  // 将URLSearchParams对象转为普通对象
  const movieInfo = Object.fromEntries(searchParams);
  
  return <BookingSummary movieInfo={movieInfo} />;
};

// 原类组件
class BookingSummary extends React.Component {
  componentDidMount() {
    console.log('电影信息:', this.props.movieInfo);
  }

  render() {
    return <div>预订汇总页面</div>;
  }
}

export default BookingSummaryWrapper;
  1. 更新App.js中的路由配置:
function App(){
    return(
     <Routes>
       <Route path="/bookingSummary" element={<BookingSummaryWrapper/>}/>
     </Routes>
    )}

补充说明:如果是临时需求,也可以直接使用全局的window.location.search解析参数,但这种方式绕开了React Router的路由上下文,在哈希路由等场景下可能出现问题,不推荐长期使用。

内容的提问来源于stack exchange,提问作者Ryan Fonseka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:06:29