【问题标题】:Get URL pathname in nextjs在 nextjs 中获取 URL 路径名
【发布时间】:2021-08-12 03:45:19
【问题描述】:

我有一个登录页面和布局组件。布局组件有标题。我不想在登录时显示标题。为此我想获取 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>
        )
    }
}

请帮忙

【问题讨论】:

标签: reactjs next.js


【解决方案1】:

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

【讨论】:

  • API 路由呢? Next.js API路由如何访问路由器实例?
【解决方案2】:

您可以使用asPath 属性,它会在没有配置basePathlocale 的情况下为您提供浏览器中显示的路径(包括查询):

const { asPath } = useRouter()

【讨论】:

  • asPath 是最好的解决方案。 pathName 或 baseName 不适用于 getStaticPaths
  • 谢谢,应该标记为已接受的答案。
【解决方案3】:

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

useRouter()钩子返回一个路由对象,它有两个属性来获取路径名。

  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;

【讨论】:

  • 这对于路径名返回 404 但您想访问失败 URL 的 404 页面非常有用。
【解决方案4】:

要充分使用 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>
 }
}

【讨论】:

  • 哪个上下文?您的示例没有任何上下文。
  • 原始问题也没有任何上下文
  • 啊,明白了。 context 对象已经在我的代码中用{ pathname } 解构。
【解决方案5】:

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

【讨论】:

    【解决方案6】:

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

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

    【讨论】:

    • 我觉得你不需要useState/useEffect,只需要const currentPath = router.pathname
    • @StephaneL 刚刚编辑了答案,谢谢 :)
    【解决方案7】:

    为谁搜索示例:

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

    【讨论】:

      【解决方案8】:

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

      import {useRouter} from 'next/router';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-11
        • 1970-01-01
        • 1970-01-01
        • 2022-07-29
        • 2020-07-25
        • 1970-01-01
        • 2022-08-08
        相关资源
        最近更新 更多