在 nextjs 中获取 URL 路径名

Get URL pathname in nextjs

我有一个登录页面和布局 component.Layout 组件有 header.I 不想在登录中显示 header。为此我想获得 url pathname.based 在路径名上显示 header .

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>
        )
    }
}

请帮忙

如果您想访问应用中任何功能组件内的 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>
  )
}

If useRouter is not the best fit for you, withRouter can also add the same router object to any component, here's how to use it:

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

要充分利用 Next.js 提供的开箱即用 SSR,您可以使用 getInitialProps 中提供的 context 对象,其中包含 pathname.然后,您可以将此 pathname 传递给您的组件用作 props

例如:

class Page extends React.Component {
 static getInitialProps({ pathname }){
  return { pathname }
 }
 render() {
  return <div>{this.props.pathname === 'login' ? 'good' : 'not good'}</div>
 }
}

正在为谁搜索示例:

import React, { Component } from "react";
import { withRouter } from 'next/router'

class Login extends Component {


    constructor(props) {
        super(props);
    }


    onClickHandler = (event) => {
        this.props.router.push('/newPage')

    }

    render() {
        return (

            <div>
                <p>Hello, {this.props.router.pathname}</p>
                <button onClick={this.onClickHandler}>Click me!</button>
            </div>
        );
    }
}

export default withRouter(Login);

可能是为了避免在 nextjs 中使用 import Router from 'next/router' 你可以使用

import {useRouter} from 'next/router';

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

const { asPath } = useRouter()

可能会迟到但请使用router.pathname

function MyComp() {
    const router = useRouter();

    return (
        <a className={router.pathname === '/some-path' ? 'currentCSS' : 'defaultCSS'}>
            Some link
        </a>
    );
}

无法访问 Router 或 useRouter() 选项来访问 app.js 文件中的当前路径。这不是客户端呈现的,因此访问您当前路径的唯一方法是将它从您的 getInitialProps()getServerSideProps() 调用传递给您的 App 组件,然后在那里访问它以开发您的逻辑基于当前路线。

假设一个页面的完整URL为'abc.com/blog/xyz',匹配该路由的组件文件名为'./pages/blog/[slug].js'

useRouter() hook returns 一个路由对象,它有两个属性来获取路径名。

  1. 一个是asPath属性,还有

  2. 另一个是pathname 属性.

asPath 属性 包含从 URL 中提取的路径名,即 /blog/xyz

pathname 属性 包含项目目录的路径名,即 /blog/[slug].

示例实现

// .pages/blog/[slug].js

import { useRouter } from 'next/router';

const BlogSlug = () => {
  const { asPath, pathname } = useRouter();
  console.log(asPath); // '/blog/xyz'
  console.log(pathname); // '/blog/[slug]'
  return (
    <div></div>
  );
}

export default BlogSlug;

我的应用程序需要有多个文档,所以我也在寻找一种获取路径名的方法,使用 nextjs,默认文档 这是我找到的一种方法,对我有用。

import Document, { Html, Head, Main, NextScript } from 'next/document'
import { LandingPage, WithSidePanels } from '../documents'

class MyDocument extends Document {
    static async getInitialProps(ctx) {
        const initialProps = await Document.getInitialProps(ctx)
        return { ...initialProps }
    }
    
    
    render() {
        console.log(this.props.__NEXT_DATA__.page)
        if(this.props.__NEXT_DATA__.page === "/") return <LandingPage />


        return (
           <WithSidePanels />
        )
    }
}

export default MyDocument

所以 this.props.__NEXT_DATA__.page 这将为您提供路径名称“/”或“/contact”或其他名称, 来自 _document.js :)