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

React Router如何匹配搜索栏提交生成的URL并渲染对应组件

问题原因

React Router 的 Route 组件 path 属性仅匹配 URL 的路径段,不会匹配 ? 后面的查询参数、# 后面的哈希值,所以你直接把带查询参数的完整字符串写入 path 是永远不会触发匹配的。

解决方法(适配你当前用的 React Router v5 版本)

  1. 先删除你写的 <Route path={/?search=${query}#/} component={CardGroupSearch} /> 这行无效代码
  2. 在根路径的路由规则里,通过判断查询参数是否存在,来决定渲染原首页内容还是搜索结果组件

完整代码示例

首先引入路由内置的参数解析工具:

import { useLocation } from 'react-router-dom';

在组件内获取查询参数后修改路由逻辑:

return (
    <Router>
    <Switch>
        <Route path="/" exact render={props => {
            // 解析当前URL的查询参数
            const searchParams = new URLSearchParams(props.location.search);
            // 判断是否存在search查询参数
            if (searchParams.has('search')) {
                // 有搜索参数时渲染搜索结果组件,同时可以把搜索词传给组件
                return <CardGroupSearch searchQuery={searchParams.get('search')} />
            }
            // 无搜索参数时渲染原首页内容
            return (
                <div>
                    <Navi />
                    <SearchBox />
                    <CardGroup games={postsPerPage} posts={currentPosts}  loading={loading}/>
                    <Pagination postsPerPage={postsPerPage} totalPosts={posts.length} paginate={paginate} />
                 </div> 
            )
        }}/>
        <Route path="/games/:games" exact  component={Content} />
    </Switch>
    </Router>
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:57:00