我有一个登录页面和布局组件。布局组件有标题。我不想在登录中显示标题。为此我想获取 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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
请帮忙
imj*_*red 60
如果要访问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>
)
}
Run Code Online (Sandbox Code Playgroud)
如果 useRouter 不是最适合您的,withRouter 也可以将相同的路由器对象添加到任何组件,这里是如何使用它:
import { withRouter } from 'next/router'
function Page({ router }) {
return <p>{router.pathname}</p>
}
export default withRouter(Page)
Run Code Online (Sandbox Code Playgroud)
https://nextjs.org/docs/api-reference/next/router#userouter
GMK*_*ain 25
如果您使用的是Next.js 13
usePathname
反而useRouter
'use client';
import { usePathname } from 'next/navigation';
export default function MyComponent() {
const currentPage = usePathname();
return <div>{currentPage}</div>;
}
Run Code Online (Sandbox Code Playgroud)
Rus*_*kin 15
您可以使用asPath
属性,该属性将为您提供浏览器中显示的路径(包括查询),而无需配置basePath
或locale
:
const { asPath } = useRouter()
Run Code Online (Sandbox Code Playgroud)
要完全使用 Next.js 提供的开箱即用的 SSR,您可以使用和 中context
提供的对象getInitialProps
,其中包含pathname
. 然后,您可以将其传递pathname
给props
您的组件用作 a 。
例如:
class Page extends React.Component {
static getInitialProps({ pathname }){
return { pathname }
}
render() {
return <div>{this.props.pathname === 'login' ? 'good' : 'not good'}</div>
}
}
Run Code Online (Sandbox Code Playgroud)
可能会迟到但只需使用router.pathname
function MyComp() {
const router = useRouter();
return (
<a className={router.pathname === '/some-path' ? 'currentCSS' : 'defaultCSS'}>
Some link
</a>
);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
假设一个页面的完整URL为'abc.com/blog/xyz',与该路由匹配的组件文件名为'./pages/blog/[slug].js'
useRouter()
hook 返回一个路由对象,它有两个属性来获取路径名。
一是asPath
财产,
另一个是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;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
76125 次 |
最近记录: |