Next.js中设置了basePath时,如何在不使用Link的情况下获取路径

mok*_*kpi 8 javascript node.js reactjs next.js

next.js 文档中的基本路径写道:

例如,当basePath设置为/docs时,使用/about将自动变为/docs/about。

export default function HomePage() {
 return (
   <>
     <Link href="/about">
       <a>About Page</a>
     </Link>
   </>
 )
}
Run Code Online (Sandbox Code Playgroud)

我可以在不使用 element 的情况下根据我提供的路径生成路径吗Link


以下是我的next.config,js.

module.exports = {
  reactStrictMode: true,
  basePath: '/Some_Folder',
  trailingSlash: true,
}
Run Code Online (Sandbox Code Playgroud)

我在 Next.js 项目的pages文件夹下有一个简单的页面。

import Link from 'next/link';

import firebase from '../common/firebase_init';
import 'firebase/auth';

import { useState, useEffect } from 'react';

import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';

export default function App(props) {
  const [showLoginDialog, setShowLoginDialog] = useState(false);
  useEffect(() => {
    const unsub = firebase.auth().onAuthStateChanged(user => {
      if (!user) setShowLoginDialog(true);
    });

    return () => {
      unsub();
    }
  });

  const uiConfig = {
    signInFlow: 'popup',
    signInSuccessUrl: '../', 
    // This is a path that Firebase jumps to after signing in is successful
    // '../' is the relative path, but I may move this page to a new location, 
    // or even share the code across different pages.
    //
    // So, I want to write "/" here and have Next.js Generate a correct path for me.
    // something like getLink("/")
    signInOptions: [
      firebase.auth.EmailAuthProvider.PROVIDER_ID,
    ],
  };

  return <div id="login-container">
    {showLoginDialog ? <StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={firebase.auth()} /> : null}
    <Link href="/">
      <a>Go Back</a>
    </Link>
  </div>;
}
Run Code Online (Sandbox Code Playgroud)

我想signInSuccessUrl: '../',在上面的代码中生成一个路径。

原因是,“../”是相对路径,但我可能会将此页面移动到新位置,甚至在不同页面之间共享代码(例如创建一个类)。

如果我能拥有类似的东西那就太好了getLink("/")

jul*_*ves 9

您可以利用useRouter挂钩来next/router访问basePath应用程序的当前内容。

import { useRouter } from 'next/router';

export default function App(props) {
    const router = useRouter();
    const getLink = (path) => `${router.basePath}${path}`;

    console.log(getLink('/about')); // Will log `/your-base-path/about

    // Remaining code...
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,您可以将其提取为自定义挂钩。 (2认同)