在 nextjs 中获取 URL 路径名

我有一个登录页面和布局组件。布局组件有标题。我不想在登录中显示标题。为此,我想得到基于路径名的 url pathname.show 头部。

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

请帮帮我

200088 次浏览

If you want to access the router object inside any functional component in your app, you can use the useRouter hook, here's how to use it:

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

To fully use the SSR out-of-the-box provided by Next.js, you can use the context object provided in getInitialProps and which contains the pathname. You can then pass this pathname to be used as a props by your component.

For example:

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


For whom who are searching for an example:

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

Probably to avoid use import Router from 'next/router' in nextjs you may use

import {useRouter} from 'next/router';

You can use asPath property, that will give you the path (including the query) shown in the browser without the configured basePath or locale:

const { asPath } = useRouter()

Might be late but just use router.pathname

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


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

One cannot access the Router or the useRouter() options to access the current path in app.js file. This is not client side rendered and hence the only way to access you current path would be to pass it from your getInitialProps() or the getServerSideProps() call to your App component, and then access it there to develop your logic based on the current route.

Suppose the complete URL of a page is 'abc.com/blog/xyz' and the component file name matching with this route is './pages/blog/[slug].js'

useRouter() hook returns a route object, which has two properties to get the pathname.

  1. One is asPath property, and

  2. Another one is pathname property.

asPath property contains pathname extracted from the URL i.e. /blog/xyz

but pathname property contains the pathname of your project directory i.e. /blog/[slug].

Example Implementation

// .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;

My app needed to have multiple documents, so I also was looking for a way to get the path name, with nextjs, default document This is a way that I found, which works for me.

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

So this.props.__NEXT_DATA__.page this is going to give you, the path name, "/", or "/contact" or whatever, from the _document.js :)