1

我在我的项目中使用 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 中创建查询字符串?

4

2 回答 2

1

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

const params = new URLSearchParams({
  var1: "value",
  var2: "value2",
  arr: "foo",
});
console.log(params.toString());
//Prints "var1=value&var2=value2&arr=foo"
于 2021-01-11T03:11:42.457 回答
0

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

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

例如:

 Router.push({
  pathname: currentPath,
  query: {
     page: 1,
     skip: 10
  }
})
// results into currentPath?page=1&skip=10
于 2021-09-13T09:39:50.140 回答