【问题标题】:NextJS redirect to other page without query paramsNextJS 重定向到没有查询参数的其他页面
【发布时间】:2022-01-18 01:50:34
【问题描述】:

我能够在成功登录后成功将用户重定向到相关仪表板页面。但是,在这种情况下,URI 被严重污染了'somedomain.com/v1/internal/salesman/dashboard?name=SomeName&email=someemail&uid=somenumber'。我希望做类似redirect(<DashBoard someProps={someProps}/> 的事情,而不是污染URI。是否有可能在 NextJS 中实现我想要的?

const onSubmit = async (e) => {
    e.preventDefault();
    
    const server_path = process.env.SERVER_ADDRESS;
    try{
      const res = await fetch(`${server_path}api/v1/internal/salesman/signin`, {
        method: 'post',
        headers: {
          'Accept': 'application/json, text/plain, */*',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({email: email.val, password: password.val})
      });
      if(await res.status === 200){
        const data = await res.json();
        router.push({pathname: '/internal/salesman/dashboard', query: {name: data.name, email: data.email, uid: data.uid}});
      }
    } catch(error){
      console.log(error);
    }
    
  }

【问题讨论】:

    标签: next.js nextjs-dynamic-routing


    【解决方案1】:

    您可以使用 as 参数指定您希望看到的 URL 路径。

    router.push

    router.push(url, as, options)
    

    as: UrlObject | String - 路径的可选装饰器 显示在浏览器的 URL 栏中。在 Next.js 9.5.3 之前使用过 对于动态路由,请查看我们之前的文档以了解它是如何工作的。 注意:当此路径与href 中提供的路径不同时, 之前的href/as 行为如之前的文档所示使用。

    router.push(
      {
        pathname: '/internal/salesman/dashboard',
        query: {
          name: data.name,
          email: data.email,
          uid: data.uid,
        },
      },
      '/internal/salesman/dashboard',
    );
    

    如果您想实际重定向,则可以使用 router.replace 和相同的参数。

    【讨论】:

    • 有效!感谢 Drew 编辑我的帖子并给出了很好的解释!干杯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 2012-03-16
    • 1970-01-01
    • 2020-12-14
    相关资源
    最近更新 更多