首页 > 解决方案 > 在 nextjs 中使用 router.push 清理 url

问题描述

我有下面的代码。它重定向到 /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 }
            });
          }
      });

标签: reactjsfrontendnext.jspushrouter

解决方案


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

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

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

推荐阅读