在 nextjs 中获取 URL 路径名

新手上路,请多包涵

我有一个登录页面和布局组件。布局组件有标题。我不想在登录中显示标题。为此我想获取 url 路径名。基于路径名显示标题。

 import * as constlocalStorage from '../helpers/localstorage';
import Router from 'next/router';

export default class MyApp extends App {
    componentDidMount(){
        if(constlocalStorage.getLocalStorage()){
            Router.push({pathname:'/app'});
        } else{
            Router.push({pathname:'/signin'});
        }

    }

    render() {
        const { Component, pageProps } = this.props
        return (
//I want here pathname for checking weather to show header or not
                <Layout>
                    <Component {...pageProps} />
                </Layout>
        )
    }
}

请帮忙

原文由 Karthi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 6k
2 个回答

如果您想在应用程序的任何功能组件中访问 router 对象,可以使用 useRouter 挂钩,以下是使用方法:

 import { useRouter } from 'next/router'

export default function ActiveLink({ children, href }) {
  const router = useRouter()
  const style = {
    marginRight: 10,
    color: router.pathname === href ? 'red' : 'black',
  }

  const handleClick = e => {
    e.preventDefault()
    router.push(href)
  }

  return (
    <a href={href} onClick={handleClick} style={style}>
      {children}
    </a>
  )
}

如果 useRouter 不是最适合你的,withRouter 也可以将相同的路由器对象添加到任何组件,这里是如何使用它:

 import { withRouter } from 'next/router'

function Page({ router }) {
  return <p>{router.pathname}</p>
}

export default withRouter(Page)

https://nextjs.org/docs/api-reference/next/router#userouter

原文由 imjared 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 asPath 属性,这将为您提供浏览器中显示的路径(包括查询),无需配置 basePathlocale :01—

 const { asPath } = useRouter()

原文由 Ruslan Korkin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进