首页 > 解决方案 > 在 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>
        )
    }
}

请帮忙

标签: reactjsnext.js

解决方案


如果您想访问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


推荐阅读