我在我的项目中使用 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 中创建查询字符串?
答案 0 :(得分:0)
您可以使用 URLSearchParams 来简化您的代码
const params = new URLSearchParams({
var1: "value",
var2: "value2",
arr: "foo",
});
console.log(params.toString());
//Prints "var1=value&var2=value2&arr=foo"