在next.js中获取客户端的当前URL [英] Getting the current url on the client side in next.js
问题描述
因此,我正在开发一个nodejs应用程序,我将在其上拥有新网站,并且我想为我的用户提供一种方法,使其在客户端显示不同的内容,并根据用户所按下的内容进行重新渲染.我的想法是,例如,首先用户将看到请先选择一个工具",然后用户将在导航栏中选择一个工具,然后将重新渲染该页面,并在巨无霸内显示所选工具,其网址为例如,先更改为/admin/[ToolSelected].
So I am working on a nodejs app which I will have my new website on and I want to make a way for my user on the clientside to display different things, re-renderd depending on what the user is pressing on. My idea is that for example firstly the user would see "Please select a tool first" and then the user will select a tool in the navbar which then the page will be re-renderd and display the tool selected inside a jumbotron with the url being changed for example then /admin/[ToolSelected].
唯一的原因是我不知道如何实现这一目标.我以为客户端代码可以检测到url是什么,并将其作为页面变量放置,然后根据页面变量是什么,该工具将与IF语句一起显示.
The only thing is tho that I do not know how to achieve this. I was thinking that the client side code could detect what the url is and is placed as a page variable then the tool will displayed with a IF statement depending on what the page variable is.
我的理论会起作用吗?或者如何有效地实现这一目标?
这是我的主页代码:
// Including Navbar and css
import AdminLayout from '../comps/admin/adminLayout'
// the so called "tools" more will exist in the future
import Passform from '../comps/admin/tools/passform'
// Fetching the current url the user is on
var page = CURRENT_URL;
const jumbotron = {
background: 'white'
}
const Admin = (page) => (
<AdminLayout>
<style global jsx>
{
`body {
background: #eff0f3;
}`
}
</style>
<div className="jumbotron" style={jumbotron}>
{(page == "passform") ? (
<Passform/>
) : (
<h3>Something is wrong :/ . {page}</h3>
)}
</div>
</AdminLayout>
)
export default Admin
推荐答案
您可以使用 withRouter
HOC,它将注入具有当前pathname
的router
对象.
import { withRouter } from 'next/router';
const Admin = ({ router }) => (
<AdminLayout>
<style global jsx>
{`
body {
background: #eff0f3;
}
`}
</style>
<div className="jumbotron" style={jumbotron}>
{router.pathname == 'passform' ? <Passform /> : <h3>Something is wrong :/ . {page}</h3>}
</div>
</AdminLayout>
);
export default withRouter(Admin);
修改
如果您喜欢钩子,则可以使用 useRouter
钩子
If you prefer hooks you can use useRouter
hook.
import { userRouter } from 'next/router';
const Admin = () => {
const router = useRouter();
return (
<AdminLayout>
<style global jsx>
{`
body {
background: #eff0f3;
}
`}
</style>
<div className="jumbotron" style={jumbotron}>
{router.pathname == 'passform' ? <Passform /> : <h3>Something is wrong :/ . {page}</h3>}
</div>
</AdminLayout>);
}
;
export default withRouter(Admin);
这篇关于在next.js中获取客户端的当前URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!