制作nextjs< link>尊重默认的“重定向”中间件

发布于 2025-02-05 08:52:28 字数 959 浏览 0 评论 0原文

我正在使用React和NextJS版本12,并希望重定向这两个URL:

  • http:// localhost:3000
  • http:// localhost:3000/code>

都应该转到

  • http:// localhost:3000/dashboard

我有以下重定向中间件设置:

async redirects() {
  return [
    {
      source: '/',
      destination: '/dashboard',
      permanent: false,
    },
  ];
},

如果我在地址栏上键入上方的任何一个URL,则可以使用。但是,这不起作用:

<Link href="/">dashboard</Link>

这将把我发送到root(后备页面,以防万一我们需要它)的index.tsx.tsx.tsx.tsx.tsx.tsx.tsx。 // localhost:3000 。它应重定向到http:// localhost/dashboard

也许我对服务器上的运行与客户端上的运行感到困惑?我来自Angular,路线和重定向是为客户端(或两者兼而有之,我相信使用SSR)。

如何使链接尊重NextJS中的内置重定向中间件?还是我编写自定义中间件的唯一选择?

I'm using React and NextJS version 12 and want to redirect these two URLs:

  • http://localhost:3000
  • http://localhost:3000/

Both should go to

  • http://localhost:3000/dashboard

I have the following Redirects middleware set up:

async redirects() {
  return [
    {
      source: '/',
      destination: '/dashboard',
      permanent: false,
    },
  ];
},

This works if I type either URL above in my address bar. However, this does not work:

<Link href="/">dashboard</Link>

This will instead send me to the index.tsx at the root (a fallback page, just in case we'd ever need it) at the URL http://localhost:3000. It should redirect to http://localhost/dashboard.

Perhaps I'm confused about what runs on the server versus on the client? I come from Angular where the routes and redirects are for client (or both, when using SSR, I believe).

How do I make the Link respect the built in Redirects middleware from NextJS? Or is my only option to write custom middleware?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

壹場煙雨 2025-02-12 08:52:30

一种解决方案是在您的index.tsx上添加useffect

import React, { useEffect } from "react";
import Router from "next/router";

const Home = (props: any) => {
  useEffect(() => {
    const { pathname } = Router;
    if (pathname === "/") {
      Router.push("/dashboard");
    }
  });
  return <></>;
};

export default Home;

A solution is to add an UseEffect on your index.tsx:

import React, { useEffect } from "react";
import Router from "next/router";

const Home = (props: any) => {
  useEffect(() => {
    const { pathname } = Router;
    if (pathname === "/") {
      Router.push("/dashboard");
    }
  });
  return <></>;
};

export default Home;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文