从/重定向到另一个页面的Next.js重定向

187

我是Next.js的新手,想知道如何将起始页面(/)重定向到例如/hello-nextjs。一旦用户加载页面,确定路径是否为/,就将其重定向到/hello-nextjs

react-router中,我们会做类似以下的操作:

<Switch>
  <Route path="/hello-nextjs" exact component={HelloNextjs} />
  <Redirect to="/hello-nextjs" /> // or <Route path="/" exact render={() => <Redirect to="/hello-nextjs" />} />
</Switch>

1
你想要重定向发生的时候? - Nico
19个回答

4

我已经在我的Next.JS应用程序中实现了这个功能,通过定义一个根页面,在服务器端和客户端进行重定向。以下是根页面的代码:

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

const redirectTo = "/hello-nextjs";

const RootPage = () => {
  useEffect(() => Router.push(redirectTo));
  return null;
};
RootPage.getInitialProps = (ctx) => {
  if (ctx.req) {
    ctx.res.writeHead(302, { Location: redirectTo });
    ctx.res.end();
  }
};

export default RootPage;

它很可能会在静态导出时失败,因为在此上下文中未定义ctx.res.writeHead。 - Eric Burel

3

‍♂️ useEffect 会重定向但立即跳回当前页面。

useLayoutEffect 非常有效:

const router = useRouter();

useLayoutEffect(() => {
  router.isFallback && router.replace("/course");
}, [router]);

ℹ️ 我已经在上面的代码中使用了相同的 useEffect。


2
如果您的意图是确保您的应用程序像 SPA 一样运行,并且想要拦截用户粘贴到地址栏中的无效(或有效)路径名,则可以使用以下快速 / 粗略方法。
假设您的路径为,
enum ERoutes {
  HOME = '/',
  ABOUT = '/about',
  CONTACT = '/contact'
}

如果您还没有自定义的_error页面,请添加一个,并将以下内容添加到其中:
import React from 'react';
import { NextPage } from 'next';
import { useDispatch } from 'react-redux';
import { useRouter } from 'next/router';

const Error: NextPage = () => {
    const { asPath, push } = useRouter();
    const dispatch = useDispatch();

    React.useEffect(() => {
        const routeValid = Object.values(ERoutes).includes(asPath);

        if (routeValid) {
          // do some stuff, such as assigning redux state to then render SPA content in your index page
        } else {
          // you can either continue to render this _error component, or redirect to your index page,
          // where you may have your own error component that is displayed based on your app state.
          // In my case, I always redirect to '/' (as you can see below, where I push('/'), but before doing so,
          // I dispatch relevant redux actions based on the situation
        }

        // I redirect to root always, but you can redirect only if routeValid === true
        push('/');
    }, []);

    return (
        <div>Error because '{asPath}' does not exist</div>
    );
};

export default Error;

1

这是对我有效的方法。使用禁用appDir的Next.js >= 13.2。

如果您想要重定向和改变URL(即浏览器从/ -> /hello-nextjs)。创建一个名为middleware.ts(或middleware.js)的文件,并将其放置在pages目录所在的文件夹中。例如,我的页面位于/src/pages,因此我们将得到/src/middleware.ts

export default async function middleware(req: NextRequest) {
    const { pathname } = req.nextUrl;
    if (pathname === "/") {
        // Redirect from /-> /hello-nextjs
        return NextResponse.redirect(new URL("/hello-nextjs", req.nextUrl));
    }
    return NextResponse.next();
}

注意事项:

  1. 相对URL在Next.js >=13.2中不起作用,因此我们需要像上面看到的那样改变现有的URL。(来源:middleware-relative-urls
  2. 如果您不介意URL保持不变,但仍然重定向(即/重定向到/hello-nextjs,但浏览器URL仍为/),则可以使用NextResponse.rewrite()而不是NextResponse.redirect()

1

重定向 从Next.js 9.5开始,您现在可以在next.config.js文件中的redirects键下创建重定向列表:

// next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/about',
        destination: '/',
        permanent: true,
      },
    ];
  },
};

Ofiicial Docs


0

您可以设置基本路径。Next Js 允许您这样做。例如,要使用 /login 而不是 /(默认值),请打开 next.config.js 并添加 basePath 配置:

  const nextConfig = {
  basePath: "/login",
};

module.exports = nextConfig;

你也可以在这里查看他们的文档 https://nextjs.org/docs/api-reference/next.config.js/basepath


0

这里是中间件解决方案,可以避免出现“URL格式错误,请仅使用绝对URL”的错误。

此外,使用路径对象可能是处理重定向的更清晰的方式。

// pages/_middleware.ts

import { NextRequest, NextResponse } from 'next/server';

export async function middleware(req: NextRequest) {
  const { pathname, origin } = req.nextUrl;

  const paths: { [key: string]: string } = {
    '/admin/appearance': `${origin}/admin/appearance/theme`,
  };

  const rePath = paths[pathname];
  if (rePath) return NextResponse.redirect(rePath);
  else return NextResponse.next();
}

0
在Next.js中,您可以使用useEffect()钩子与useRouter()钩子结合来实现重定向。 useEffect()钩子将用于在页面加载后执行重定向,而useRouter()钩子允许您访问当前路由信息。
以下是在Next.js中从起始页(路径为“/”)重定向到“/hello-nextjs”的示例:
import { useEffect } from 'react';
import { useRouter } from 'next/router';

const Home = () => {
  const router = useRouter();

  useEffect(() => {
    // Check if the current path is "/"
    if (router.pathname === "/") {
      // Redirect to "/hello-nextjs"
      router.push("/hello-nextjs");
    }
  }, [router]);

  return (
    <div>
      {/* Your home page content goes here */}
    </div>
  );
};
export default Home;

0
import Link from "next/link";

const Header = () => {

    return (
        <div>
            <nav>
                <ul>
                    <li> <Link href='/home'>Home </Link></li>
                    <li> <Link href='/about'>About </Link></li>
                    <li> <Link href='/contact'>Contact US </Link></li>
                </ul>
            </nav>
        </div>
    );
};
export default Header;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接