【问题标题】:Next.js router create query string and query string arrayNext.js 路由器创建查询字符串和查询字符串数组
【发布时间】:2021-09-13 17:39:50
【问题描述】:

我在我的项目中使用 Next.js,我需要创建一个动态查询字符串。我使用此代码:

const createQuery = (filter) => {
  let currentPath = router.pathname;
  let filterSize = Object.keys(filter).length;

  filterSize != 0 ? (currentPath += "?") : null;

  Object.keys(filter).map(function (key, index) {
    currentPath +=
      key + "=" + filter[key] + (index === filterSize - 1 ? "" : "&");
  });

  router.push(currentPath);
};

它有效,但我不向查询字符串发送数组。我怎样才能做到这一点?另外,有没有更简单的方法在 Next.js 中创建查询字符串?

【问题讨论】:

    标签: reactjs routes next.js next-router


    【解决方案1】:

    您可以使用URLSearchParams 来简化您的代码

    const params = new URLSearchParams({
      var1: "value",
      var2: "value2",
      arr: "foo",
    });
    console.log(params.toString());
    //Prints "var1=value&var2=value2&arr=foo"
    

    【讨论】:

      【解决方案2】:

      您可以使用nextjs/router轻松传递动态查询字符串

      Router.push 接受query 作为将转换为查询参数的对象。

      例如:

       Router.push({
        pathname: currentPath,
        query: {
           page: 1,
           skip: 10
        }
      })
      // results into currentPath?page=1&skip=10
      

      【讨论】:

        猜你喜欢
        • 2015-04-12
        • 2014-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多