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

Next.js 14页面传值报错:Uncaught TypeError: path.startsWith is not a function

问题排查与解决方案

错误1:Uncaught TypeError: path.startsWith is not a function

这个错误源于Next.js 14 App Router与Pages Router的router.push参数格式差异,你参考的回答适配Pages Router,在App Router中不适用:

  • App Router里,router.push的对象参数需要用searchParams而非query字段传递URL查询参数。
  • 错误的query字段会导致路由无法正确解析路径,触发path.startsWith类型错误。

Page A 修正代码

import { useRouter } from 'next/navigation';

const handleNavigate = (campaign) => {
  router.push({
    pathname: `/campaign-details/${campaign.pId}`,
    // 替换query为searchParams
    searchParams: {
      owner: campaign.owner,
      name: campaign.name,
      title: campaign.title,
      description: campaign.description,
      target: campaign.target.toString(), // 注意:searchParams的值必须是字符串,非字符串类型需转换
      deadline: campaign.deadline.toString(),
      amountCollected: campaign.amountCollected.toString(),
      image: campaign.image,
      pId: campaign.pId,
    },
  });
};

额外提醒:searchParams的所有值必须是字符串(或字符串数组),如果campaign里有数字、日期等非字符串类型,必须先转换,否则会触发隐性错误。

错误2:useSearchParams使用不当

Page B中searchParams.get(title)的写法存在两个问题:

  • get方法需要传入参数名的字符串,而非变量(除非你提前定义title为字符串'title')。
  • 代码中使用的category参数并未在Page A的查询参数中传递,会返回null。

Page B 修正代码

import { useSearchParams } from 'next/navigation';

// ...

const searchParams = useSearchParams();

<div>
  <h4 className="font-semibold text-[18px] text-white uppercase">
    {searchParams.get('title')}
  </h4>

  <p className="mt-[3px] font-normal text-[16px] leading-[18px] text-[#808191]">
    {/* 如果需要category参数,需在Page A的searchParams中添加该字段 */}
    {searchParams.get('owner')} {/* 示例:使用实际传递的参数名 */}
  </p>
</div>

更优方案:通过state传递数据(不暴露在URL)

如果数据不需要展示在URL中,推荐用state传递,避免URL过长或敏感数据暴露:

Page A 代码

const handleNavigate = (campaign) => {
  router.push(`/campaign-details/${campaign.pId}`, { 
    state: { campaign } 
  });
};

Page B 获取state

import { useRouter } from 'next/navigation';

const router = useRouter();
// 从router.state中获取传递的campaign数据
const campaign = router.state?.campaign;

// 使用数据
<div>
  <h4 className="font-semibold text-[18px] text-white uppercase">
    {campaign?.title}
  </h4>
  <p className="mt-[3px] font-normal text-[16px] leading-[18px] text-[#808191]">
    {campaign?.owner}
  </p>
</div>

注意:state数据存储在浏览器history栈中,刷新页面后会丢失,若需持久化数据,建议用URL参数或其他存储方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 07:27:39