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

Next Router与NextPage类型不兼容报错问题求助

解决Next.js动态路由中的TypeScript错误

问题场景

为原本仅支持静态路由的Next.js应用实现动态路由时,遇到TypeScript类型错误,代码及报错信息如下:

原代码

import { NextPage } from 'next';
import { useRouter } from 'next/router';
// import CardWhitData from 'src/components/molecules/cardWhitData';
import FloatCard from 'src/components/atoms/floatCard';

const Event: NextPage = () => (
  const router = useRouter()
  const {index} = router.query
  <>
    <FloatCard
      mainTitle="This is your event"
      description="This is your description"
    />
  </>
)
export default Event;

报错信息

Type '() => (: any, router: NextRouter | undefined, : any, { index }?: boolean) => any' is not assignable to type 'NextPage<{}, {}>'.
  Type '() => (: any, router: NextRouter | undefined, : any, { index }?: boolean) => any' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext<any>): {} | Promise<{}>; }'.
    Type '() => (: any, router: NextRouter | undefined, : any, { index }?: boolean) => any' is not assignable to type 'FunctionComponent<{}>'.
      Type '(: any, router: NextRouter | undefined, : any, { index }?: boolean) => any' is not assignable to type 'ReactElement<any, any>'.ts(2322)

错误原因及修复方案

核心问题

箭头函数使用圆括号()包裹函数体,但函数体内包含变量声明语句,这种写法不符合React函数组件语法规范。圆括号仅能直接返回单个表达式,无法容纳多个语句;必须改用大括号{}包裹函数体,并显式返回JSX内容。

修正后的代码

import { NextPage } from 'next';
import { useRouter } from 'next/router';
// import CardWhitData from 'src/components/molecules/cardWhitData';
import FloatCard from 'src/components/atoms/floatCard';

const Event: NextPage = () => {
  const router = useRouter();
  const { index } = router.query;
  
  return (
    <>
      <FloatCard
        mainTitle="This is your event"
        description="This is your description"
      />
    </>
  );
};
export default Event;

额外说明

  • 函数体改用大括号{}后,必须通过return语句返回JSX结构
  • 变量声明末尾建议添加分号,符合TypeScript代码规范
  • 动态路由初始加载时router.query可能为空,若需处理index为undefined的情况,可添加类型断言或可选链,例如const index = router.query.index as string;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:33:21