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

使用LinkContainer时出现pathname含?字符的Uncaught Error求助

LinkContainer路由查询参数错误解决方案

错误信息

Uncaught Error: Cannot include a '?' character in a manually specified to.pathname field [{"pathname":"/search?category=Cameras"}]. Please separate it out to the to.search field. Alternatively you may provide the full path as a string in and the router will parse it for you.

解决方法

方法1:拆分路径与查询参数(推荐)

按照错误提示,将to属性设置为对象,分别指定pathname和search字段,避免在路径中直接拼接查询参数:

<LinkContainer
  to={{
    pathname: '/search',
    search: `?category=${category}`
  }}
  onClick={() => setSidebarOpen(false)}
>
  <Nav.Link>{category}</Nav.Link>
</LinkContainer>

如果使用React Router v6及以上版本,更推荐使用searchParams来构建查询参数,无需手动拼接?:

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

// ...

<LinkContainer
  to={{
    pathname: '/search',
    searchParams: { category: category }
  }}
  onClick={() => setSidebarOpen(false)}
>
  <Nav.Link>{category}</Nav.Link>
</LinkContainer>

方法2:直接传递完整路径字符串

如果希望保持字符串形式,确保to直接接收完整路径字符串,部分react-router-bootstrap版本支持自动解析路径与查询参数:

<LinkContainer
  to={`/search?category=${category}`}
  onClick={() => setSidebarOpen(false)}
>
  <Nav.Link>{category}</Nav.Link>
</LinkContainer>

注:若此方式仍报错,优先选择方法1,部分旧版本对字符串路径的解析逻辑更严格。

差异说明

react-router-dom的Link组件会自动将带?的字符串路径拆分为pathname和search字段,而LinkContainer(来自react-router-bootstrap)会对手动指定的pathname进行严格校验,因此需要显式拆分参数或确保字符串路径被正确解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:15:37