reactjs - 在 nextjs 中获取 URL 路径名
问题描述
我有一个登录页面和布局组件。布局组件有标题。我不想在登录中显示标题。为此我想获取 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>
)
}
}
请帮忙
解决方案
如果您想访问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)
推荐阅读
- c# - 使用 TaskCompletionSource 构建 IAsyncEnumerable
- node.js - 从集合 mongodb nodejs 中获取随机 id
- python - Python:运行长度编码?
- swift - @State 更改时 SwiftUI 视图不更新
- python - 在 Python 中构建质数可迭代对象
- vue.js - Vue 应用企业版:如何为开源软件项目管理干净的代码库
- python - 如何避免 Delaunay.find_simplex 函数返回 -1
- c# - .NET Core - Novell LDAP/AD - 组搜索他所属的用户 - 有人让它工作吗?
- angular - 此条件将始终返回 'false',因为类型 'number' 和 'string' 没有重叠 ngIf
- apache - XAMPP Apache 服务器为 REST API 发出不需要的 301 重定向