在nextjs中获取URL路径名 [英] Get URL pathname in nextjs

查看:105
本文介绍了在nextjs中获取URL路径名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

import * as constlocalStorage from '../helpers/localstorage';从下一个/路由器"导入路由器;导出默认类 MyApp 扩展 App {componentDidMount(){if(constlocalStorage.getLocalStorage()){Router.push({pathname:'/app'});} 别的{Router.push({pathname:'/signin'});}}使成为() {const { Component, pageProps } = this.props返回 (//我想在这里检查天气的路径名是否显示标题<布局><组件{...pageProps}/></布局>)}}

请帮忙

解决方案

如果您想访问应用中任何功能组件内的 router 对象,您可以使用 useRouter钩子,这里是如何使用它:

import { useRouter } from 'next/router'导出默认函数 ActiveLink({ children, href }) {const 路由器 = useRouter()常量样式 = {边距:10,颜色:router.pathname === href ?'红黑',}const handleClick = e =>{e.preventDefault()router.push(href)}返回 (<a href={href} onClick={handleClick} style={style}>{孩子们}</a>)}

<块引用>

如果 useRouter 不是最适合您的,withRouter 还可以将相同的路由器对象添加到任何组件,以下是使用方法:

import { withRouter } from 'next/router'功能页面({路由器}){返回 <p>{router.pathname}</p>}导出默认 withRouter(Page)

https://nextjs.org/docs/api-reference/next/路由器#userouter

I have a signin page and layout component.Layout component has header.I don't want to show header in signin .and for that I want to get url pathname.based on pathname show the 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>
        )
    }
}

please help

解决方案

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

这篇关于在nextjs中获取URL路径名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆