因此,我正在开发一个 Nodejs 应用程序,我将在该应用程序上建立我的新网站,并且我想为客户端的用户提供一种显示不同内容的方法,根据用户按下的内容重新呈现。我的想法是,例如,首先用户会看到“请先选择一个工具”,然后用户将在导航栏中选择一个工具,然后页面将重新渲染并显示在大屏幕中选择的工具,其网址为例如更改/admin/[ToolSelected]。
唯一的问题是我不知道如何实现这一目标。我认为客户端代码可以检测 url 是什么,并将其作为页面变量放置,然后该工具将根据页面变量是什么显示 IF 语句。
我的理论可行吗?或者如何以有效的方式实现这一目标?
这是我的主页代码:
// 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 https://nextjs.org/docs/api-reference/next/router#withrouterHOC,这将注入router
对象,具有当前pathname
.
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 https://nextjs.org/docs/api-reference/next/router#userouter hook.
import { useRouter } 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 Admin;
router.pathname
将包含“config”url,因此对于动态路由,它将包含[paramName]
parts.
动态路线
您可以检查router.query https://nextjs.org/docs/pages/building-your-application/routing/dynamic-routes#example对于动态部分的存在。
import { useRouter } from 'next/router';
// assume that your dynamic route us `/static/[dynamicPart]`
const Admin = () => {
const router = useRouter();
return (
<AdminLayout>
<style global jsx>
{`
body {
background: #eff0f3;
}
`}
</style>
<div className="jumbotron" style={jumbotron}>
{router.query.dynamicPart == 'passform' ? <Passform /> : <h3>Something is wrong :/ . {page}</h3>}
</div>
</AdminLayout>);
};
export default Admin;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)