next.js 如何构造可以存储查询参数的多个值的URL

kmpatx3s  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(120)

我使用查询参数来存储选中复选框的值,但是我只能存储查询参数的一个值,如果我尝试存储另一个值,它会用新值替换该查询参数的值。我希望我的URL看起来像这样:https://myapp.com/?s=6432bc97cbde9,64bd7707c0397eda
但在当前行为中,它更新s的值,而不是附加新值。
我的代码:

"use client";

const MyComponent = ({ title, options, initialFacets }) => {
  const searchParams = useSearchParams();
  const router = useRouter();
  const titleName = title.toLowerCase();
  const selectedFilter = searchParams.get(titleName);

  const toggleOption = (optionValue) => {
    const optionUrl = `/?${createQueryString(
      searchParams,
      titleName,
      optionValue
    )}`;

    router.replace(optionUrl, { scroll: false });
  };

  return (
    <CommandGroup>
      {options.map((option) => {
        return (
          <CommandItem
            key={option.value}
            onSelect={() => toggleOption(option.value)}
            className="cursor-pointer"
          >
            <div
              className={cn(
                "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
                selectedFilter === option.value
                  ? "bg-primary text-primary-foreground"
                  : "opacity-50 [&_svg]:invisible"
              )}
            >
              <CheckIcon className={cn("h-4 w-4")} />
            </div>
          </CommandItem>
        );
      })}
    </CommandGroup>
  );
};
iugsix8n

iugsix8n1#

这样,您的URL将为同一个查询参数提供多个值,用逗号分隔,就像您想要的那样。

"use client";

const MyComponent = ({ title, options, initialFacets }) => {
  const searchParams = useSearchParams();
  const router = useRouter();
  const titleName = title.toLowerCase();
  const selectedFilter = searchParams.get(titleName);

  const toggleOption = (optionValue) => {
    let existingValues = searchParams.get(titleName);
    let newValues;

    if (existingValues) {
      if (existingValues.includes(optionValue)) {
        newValues = existingValues
          .split(",")
          .filter((value) => value !== optionValue)
          .join(",");
      } else {
        newValues = `${existingValues},${optionValue}`;
      }
    } else {
      newValues = optionValue;
    }

    // Update only the specific query param without affecting others
    searchParams.set(titleName, newValues);

    const optionUrl = `/?${searchParams.toString()}`;
    router.replace(optionUrl, { scroll: false });
  };

  return (
    //... (rest of your component logic)
  );
};

相关问题