【问题标题】:NextJS: Push new query string value to an existing asPath or update the existing query stringNextJS:将新的查询字符串值推送到现有的 asPath 或更新现有的查询字符串
【发布时间】:2020-08-16 22:02:45
【问题描述】:

我对 NextJS 路由器系统的工作原理有点迷茫:

我的文章按类别分类:

Medical
Charity
Wedding
Funeral

我有一个导航栏,用户可以在其中按类别显示文章,也可以按关键字搜索。类别功能运行良好。

这是我的导航栏的样子:

这意味着如果用户点击All,我们将显示所有文章:

这是场景:

  • 例如,当我们单击Medical 时,URL 如下所示:http://localhost:3000/articles?category=medical
  • 当我们点击all时,URL看起来像http://localhost:3000/articles
  • 当我们点击all并搜索关键字COVID时,URL看起来像这样:http://localhost:3000/articles?search=covid

问题

我现在想结合类别和搜索: 如果用户点击 medical 并搜索关键字 COVID,则 URL 必须如下所示:http://localhost:3000/articles?category=medical&search=covid

得到搜索结果后,当用户更改关键字时,我想将search查询字符串替换为新值。

我是怎么做的?

我知道 NextJS 路由器 object 有:

  • pathname:当前路线。也就是/pages中页面的路径
  • asPath:浏览器中显示的实际路径(包括查询)
const { push, asPath } = useRouter();

const onSearchKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    const keyword = e.currentTarget.value;
    if (e.key === "Enter") {
      url = !isEmpty(keyword.trim())
        ? {
          pathname: asPath,
          query: { search: keyword },
        }
        : {
          pathname,
        };
      push(url);
    }
  };

但这样做会编码 asPath 并导致此 URL:http://localhost:3000/article%3Fcategory=covid&amp;search=covid 显示未找到 404 页面。

所以,当用户想要执行新搜索时,我什至不知道是否可以将 search 替换为新值。

【问题讨论】:

    标签: reactjs typescript next.js


    【解决方案1】:

    我通过不使用asPath 解决了这个问题:我在扩展运算符旁边使用了pathname,如下所示:

    url = !isEmpty(keyword.trim())
         ? {
            pathname,
            query: { ...query, search: keyword },
         }: {
            pathname: page,
         };
    

    【讨论】:

      猜你喜欢
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      相关资源
      最近更新 更多