如何修复`作为值属性传递给上下文提供程序的数组更改每个呈现` typescript错误

ovfsdjhp  于 2023-10-22  发布在  TypeScript
关注(0)|答案(1)|浏览(172)

我有一个上下文和一个提供程序如下:

const SearchParamsStateProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [searchParams, setSearchParams] = useSearchParams();

  return (
    <SearchParamsStateContext.Provider value={[searchParams, setSearchParams]}>
      {children}
    </SearchParamsStateContext.Provider>
  );
};

const SearchParamsStateContext = createContext<
  [searchParams: URLSearchParams, setSearchParams: SetURLSearchParams]
>([
  new URLSearchParams(''),
  (
    search?:
      | URLSearchParamsInit
      | ((prev: URLSearchParams) => URLSearchParamsInit),
  ) => search,
]);

打印脚本在行中抛出错误:value={[searchParams, setSearchParams]}
作为值prop传递给Context提供程序的数组(在第12行)在每次呈现时都会更改。要解决这个问题,请考虑将其 Package 在useMemo钩子中。
所以我尝试使用useMemo:

const value = useMemo(
    () => [searchParams, setSearchParams],
    [searchParams, setSearchParams],
  );

  return (
    <SearchParamsStateContext.Provider value={value}>
      {children}
    </SearchParamsStateContext.Provider>
  );

但没有成功:

Type '(URLSearchParams | SetURLSearchParams)[]' is not assignable to type '[searchParams: URLSearchParams, setSearchParams: SetURLSearchParams]'.
  Target requires 2 element(s) but source may have fewer.

由于某种原因,useMemo返回的类型是:(URLSearchParams | SetURLSearchParams)[]应该在哪里:[searchParams: URLSearchParams, setSearchParams: SetURLSearchParams]

pftdvrlh

pftdvrlh1#

您的数组类型正在被泛化。尝试在备忘录中的返回数组后添加as const,或者在useMemo调用中添加显式类型参数。

const value = useMemo(
  () => [searchParams, setSearchParams] as const,
  [searchParams, setSearchParams],
);

const value = useMemo<[URLSearchParams, SetURLSearchParams]>(
  () => [searchParams, setSearchParams],
  [searchParams, setSearchParams],
);

相关问题