如何在 NextJS v13 中使用 Exits 查询参数(而不是删除)设置新的查询参数

how to set new query params with exits query params (not delete) in nextjs v13

提问人:Hasan 提问时间:9/21/2023 更新时间:9/21/2023 访问量:114

问:

"use client";
import { useCallback, useEffect, useState } from "react";
import Accordion from "../accordion/accordion";
import {
  useRouter,
  usePathname,
  useSearchParams,
  useParams,
} from "next/navigation";
import { getBrandsRequest } from "../../../APIRequest/brand/brandApi";
import capitalizeFLetter from "../../../utils/capitalizedFirstWord/capitalizedFirstWord";

const Brand = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [allBrand, setAllBrand] = useState([]);
  const newSearchParams = new URLSearchParams(searchParams);

  const handleChange = (e, index) => {
    newSearchParams.set("tab", "cami");
  };

  useEffect(() => {
    (async () => {
      let data = await getBrandsRequest();
      setAllBrand(data);
    })();
  }, []);

  let content = (
    <>
      {allBrand?.map((item, index) => (
        <div className="flex items-center gap-x-2" key={index}>
          <label className="dark:text-white sm:text-[14px] flex items-center">
            <input
              className="w-4 sm:w-3 h-4 mr-2 accent-[#ff007f]"
              name={item?.name}
              onChange={(e) => handleChange(e, index + 1)}
              type="checkbox"
              value={item?.name}
            />
            {capitalizeFLetter(item?.name)}
          </label>
        </div>
      ))}
    </>
  );

  return (
    <div className=" max-w-[275px] px-5 border border-gray-200 rounded-lg shadow card w-96 bg-base-100 bg-white dark:bg-gray-700">
      <Accordion title={"Brand"} content={content} />
    </div>
  );
};

export default Brand;

当我单击复选框时,运行以下代码:

  const handleChange = (e, index) => {
    newSearchParams.set("tab", "cami");
  };

但这是 Show Me Null。

我必须使用这样的查询参数完成 url:http://localhost:3000/store?pageNo=1&perPage=100&searchKeyword=samsung&min=0&max=8000

我想:http://localhost:3000/store?pageNo=1&perPage=100&searchKeyword=samsung&min=0&max=8000&tab=cami

JavaScript ReactJS next.js

评论


答:

0赞 Diego Betto 9/21/2023 #1

您可以创建一个钩子来更改参数(甚至替换它们)。 这是一个简单的例子

export const useQueryParams = () => {
  const [queryParams, setQueryParams] = useSearchParams();
  const prevQueryParamsRef = useRef({});

  const filterValues = (values, options) => {
    const newQueryParams = createSearchParams(Object.keys(values).reduce((acc, curr) => {
      if (
        !Array.isArray(values[curr]) && values[curr]
        || Array.isArray(values[curr]) && values[curr].length > 0
      ) {
        acc[curr] = values[curr];
      }
      return acc;
    }, {}));

    setQueryParams(newQueryParams, {
      ...options,
      ...{
        state: options?.state || window.history.state,
      },
    });
  };

  const out = {};

  queryParams.forEach((v, k) => {
    out[k] = v;
  });

  useEffect(() => {
    prevQueryParamsRef.current = out;
  }, [out]);

  return [out, filterValues, prevQueryParamsRef.current];
};

然后,你可以用这样的代码更新一个参数

const [queryParams, setQueryParams] = useQueryParams();

setQueryParams({
  ...queryParams,
  ...{
    page: 3,
  },
});

或者,如果要替换所有参数

const [queryParams, setQueryParams] = useQueryParams();

setQueryParams({
  ...queryParams,
  ...{
    page: 3,
  },
}, {replace: true}); // <-- add this

评论

0赞 Hasan 9/26/2023
从哪里导入 useSearchParams() 和 createSearchParams() 钩子?
0赞 Diego Betto 9/27/2023
只需使用第一个代码块中的内容创建一个文件(例如 queryParams.js),然后从那里导入
0赞 Hasan 10/1/2023
ReferenceError:未定义 createSearchParams
0赞 Diego Betto 10/2/2023
导入它import { useSearchParams } from 'react-router-dom';
0赞 Hasan 10/4/2023
但是我使用 NextJS v13.4 那为什么我要 react-router-dom 包呢?