gpt4 book ai didi

reactjs - Next.JS useRouter 只会为动态路由返回一个空对象

转载 作者:行者123 更新时间:2023-12-04 02:32:24 27 4
gpt4 key购买 nike

我正在 Next.JS 中制作一些专门的日历应用程序,我在动态路由方面遇到了一些我似乎无法弄清楚的问题。我有两个具有相似路由的相似页面,其中一个工作得很好,另一个根本不工作。

第一页(工作):

// pages/date/[year]/[month]/[dayOfMonth].tsx
import { useRouter } from "next/router";
import { Day } from "../../../../components/Day";

type StringQueryParams = Record<keyof QueryParams, string>;

interface QueryParams {
year: number;
month: number;
dayOfMonth: number;
}

const transformParams = ({ year, month, dayOfMonth }: StringQueryParams): QueryParams => ({
year: parseInt(year),
month: parseInt(month),
dayOfMonth: parseInt(dayOfMonth),
});

const DayPage: React.FC = () => {
const { query } = useRouter();
const params = transformParams(query as StringQueryParams);
return <Day {...params} />;
};

export default DayPage;

第二页(不工作)

// pages/date/[year]/[month].tsx
import { useRouter } from "next/router";
import { Month } from "../../../components/Month";
import { validateMonth } from "../../../lib/month";

type StringQueryParams = Record<keyof QueryParams, string>;

interface QueryParams {
month: string;
year: number;
}

const MonthDisplay: React.FC = () => {
const router = useRouter();
debugger;
const { query } = router;
const { month: rawMonth, year: rawYear } = query as StringQueryParams;
console.log("query:", query);
console.log("router:", router);
const month = validateMonth(rawMonth);
const year = parseInt(rawYear);

return <Month name={month} year={year} />;
};

export default MonthDisplay;

有输出

query: {}
router: ServerRouter {
route: '/date/[year]/[month]',
pathname: '/date/[year]/[month]',
query: {},
asPath: '/date/[year]/[month]',
basePath: '',
events: undefined,
isFallback: false
}

我似乎无法弄清楚为什么第二页的动态路由根本不起作用,并且没有从 useRouter() Hook 返回任何查询。

最佳答案

pages/date/[year]/[month].tsx 移动到 pages/date/[year]/[month]/index.tsx 应该可以工作

关于reactjs - Next.JS useRouter 只会为动态路由返回一个空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63532120/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com