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

Next.js 13中context.query失效,求替代方案(附12版本代码)

Next.js 13 替代 context.query 的方案

首先明确:Context API 不适合用来获取 URL 参数,它是用于组件树间共享全局状态的(比如用户信息、主题配置)。你需要用以下两种方式,取决于你的组件是服务器组件还是客户端组件:

1. 服务器组件(推荐,对应原 getServerSideProps 的服务器端逻辑)

Next.js 13 App Router 中,页面/布局组件默认是服务器组件,可以直接通过组件 props 获取 searchParams:

import { notFound } from 'next/navigation';

async function CursoPage({ searchParams }: { searchParams: { id?: string; type?: string } }) {
  const { id, type } = searchParams;

  // 校验id是否存在
  if (!id) {
    return notFound();
  }

  // 调用你的数据处理函数
  const curso = await treatCursoData(undefined, id, type);

  if (!curso) {
    return notFound();
  }

  return (
    <div>
      {/* 渲染你的 curso 内容 */}
    </div>
  );
}

export default CursoPage;

这个方式和原 getServerSideProps 逻辑一致,都是在服务器端执行数据获取,适合需要SEO优化的场景。

2. 客户端组件(仅当需要客户端交互时使用)

如果你的组件需要客户端交互(比如点击事件、状态更新),需要声明为客户端组件,然后用 useSearchParams 钩子:

'use client';

import { useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { notFound } from 'next/navigation';

function CursoPage() {
  const searchParams = useSearchParams();
  const [curso, setCurso] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchCursoData = async () => {
      const id = searchParams.get('id');
      const type = searchParams.get('type');

      if (!id) {
        notFound();
        return;
      }

      const data = await treatCursoData(undefined, id, type);
      if (!data) {
        notFound();
        return;
      }

      setCurso(data);
      setLoading(false);
    };

    fetchCursoData();
  }, [searchParams]);

  if (loading) return <div>加载中...</div>;

  return (
    <div>
      {/* 渲染你的 curso 内容 */}
    </div>
  );
}

export default CursoPage;

你用 useSearchParams 失败的常见原因:

  • 忘记添加 'use client' 指令:这个钩子只能在客户端组件中使用,服务器组件会报错
  • 没有处理参数为 undefined 的情况:searchParams.get('key') 返回的是字符串或 null,需要先校验
  • 在服务器组件中尝试调用该钩子:服务器组件不能使用客户端专属钩子

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:52:21