【问题标题】:Getting the current url on the client side in next.js在 next.js 中获取客户端的当前 url
【发布时间】:2019-07-17 16:08:06
【问题描述】:

所以我正在开发一个 nodejs 应用程序,我将在该应用程序上安装我的新网站,并且我想为客户端的用户提供一种方式来显示不同的内容,并根据用户所按下的内容重新呈现。我的想法是,例如,首先用户会看到“请先选择一个工具”,然后用户将在导航栏中选择一个工具,然后页面将被重新渲染并显示在 jumbotron 内选择的工具,其 url 为例如然后更改 /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

【问题讨论】:

    标签: reactjs express next.js


    【解决方案1】:

    您可以使用withRouter HOC 包装您的组件,这将注入具有当前pathnamerouter 对象。

    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钩子。

    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;
    

    【讨论】:

    • 我想你想要import {withRouter } from 'next/router';
    • 我不知道为什么投反对票? import {withRouter} from 'next/router'; 现在是答案的一部分。这与export default withRouter(Admin); 一起工作得很好。 PS。 React 检查器是一种快速检查方法。
    • 拒绝投票,因为这不是一个可用的示例,从问题中删除了一些细节,这使得这一点更加清楚,并且缺乏对这里实际发生的事情的深入解释。
    • 我已将实现更改为使用 router.pathname
    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 2020-03-04
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 2016-01-16
    相关资源
    最近更新 更多