Next js 页面刷新时查询值丢失?[示例] [英] Query values lost on page refresh in Next js? [Example given]

查看:113
本文介绍了Next js 页面刷新时查询值丢失?[示例]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个只有两页的简单 Next Js 应用程序..

index.tsx:

从反应"导入反应;从下一个/链接"导入链接;导出默认函数 Index() {返回 (<div><链接href={{路径名:/关于",查询:{CandidateId:8432}}}as=大约">转到关于页面</链接>

);}

根据上面的代码,点击转到关于页面它转到关于页面并使用query我也在关于页面中收到传递的查询值.

about.tsx

从反应"导入反应;import Router, { withRouter } from "next/router";功能关于({路由器:{查询}}:任何){返回 (<div>候选人 ID:<b>{query.candidateId} </b>

);}导出默认 withRouter(About);

这会显示值,但是当我们在 /about 页面刷新页面时,接收到的 candidateId 消失了.

要求:请帮助我保留从一个页面传递到另一个页面的查询值,即使在页面刷新时也是如此.

注意:根据我的要求,我不应该在导航时在 url 上显示 canidateId,因此我使用 as 方法..我知道如果我删除 as 我可以实现它,但我无法在导航时在索引页面中删除它..原因是这将导致在 url 中显示不符合预期的候选 ID..

尝试了这个解决方案:

解决方案

更新到 Next.JS 10.它带有 自动解析 href 可以解决您的问题.

I am making a simple Next Js application which has only two pages..

index.tsx:

import React from "react";
import Link from "next/link";

export default function Index() {
  return (
    <div>
      <Link
        href={{
          pathname: "/about",
          query: { candidateId: 8432 }
        }}
        as="about"
      >
        Go to the about page
      </Link>
    </div>
  );
}

As per the above code, on click Go to the about page it goes to about page and using query I also receive the passed query values in about page.

about.tsx

import React from "react";
import Router, { withRouter } from "next/router";

function About({ router: { query } }: any) {
  return (
    <div>
      Candidate Id: <b> {query.candidateId} </b>
    </div>
  );
}

export default withRouter(About);

This displays the value but on page refresh while we are in /about page, the candidateId received gets disappeared.

Requirement: Kindly help me to retain the query value passed down from one page to another page even on page refresh.

Note: As per my requirement I should not display the canidateId on url while navigating and hence I am using as approach.. I know I can achieve it if I remove as but I cannot remove that here in index page while navigating.. Reason is this will lead to displaying candidateId in the url which is not intended..

Tried this solution: https://stackoverflow.com/a/62974489/7785337 but this gives empty query object on refresh of page.

Stuck for very long time with this please kindly help me.

解决方案

Update to Next.JS 10. It comes with Automatic Resolving of href which fixes your problem.

这篇关于Next js 页面刷新时查询值丢失?[示例]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆