【问题标题】:How to obtain a path without using Link when basePath is set in Next.js在 Next.js 中设置 basePath 时如何在不使用 Link 的情况下获取路径
【发布时间】:2021-09-12 13:58:28
【问题描述】:

next.js 文档中的Base Path 写道:

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

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

我可以根据我提供的路径生成路径,而不使用Link 元素吗?


以下是我的next.config,js

module.exports = {
  reactStrictMode: true,
  basePath: '/Some_Folder',
  trailingSlash: true,
}

我在 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>;
}

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

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

如果我能有 getLink("/") 这样的东西就好了。

【问题讨论】:

    标签: javascript node.js reactjs next.js


    【解决方案1】:

    您可以利用next/router 中的useRouter 挂钩来访问您应用的当前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...
    }
    

    【讨论】:

    • 谢谢。它甚至适用于生成静态网站。
    • 这样做有什么好处:const usePath = (path) =&gt; `${useRouter().basePath}${path}`;?
    • 是的,您可以将其提取为自定义挂钩。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 2014-03-02
    • 2011-05-14
    • 2016-01-29
    • 2021-12-17
    相关资源
    最近更新 更多