【问题标题】:clean urls with router.push in nextjs在 nextjs 中使用 router.push 清理 url
【发布时间】:2021-04-01 03:09:08
【问题描述】:

我有下面的代码。它重定向到 /home 并传递一个用户名变量。但是,在地址栏中,它显示 http://localhost:3000/home?username=bobmarley。如何干净利落地使用 next.js 传递变量?

import { withRouter } from 'next/router'
loginUser(this.state.user)
        .then(response => {
          var username = response['username'];

          if (username) {
            this.props.router.push({
              pathname: '/home',
              query: { username: username }
            });
          }
      });

【问题讨论】:

    标签: reactjs frontend next.js push router


    【解决方案1】:

    使用router.pushas 属性,这将是地址栏中显示的内容。将其设置为与pathname 相同的值。

    as - 将在浏览器中显示的 URL 的可选装饰器。

    this.props.router.push({
      pathname: '/home',
      as: '/home',
      query: { username: username }
    });
    

    【讨论】:

    • 嘿,我这样做了,但我的网址栏中仍然有用户名?
    【解决方案2】:

    这不是您放置 as 参数的位置。 它应该看起来像

    this.props.router.push({
      pathname: '/home',
      query: { username: username }
    },
    {
    pathname: '/masked-url'
    });
    

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 2021-04-06
      • 2021-08-03
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 2021-08-02
      相关资源
      最近更新 更多