我有一个上下文和一个提供程序如下:
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]
1条答案
按热度按时间pftdvrlh1#
您的数组类型正在被泛化。尝试在备忘录中的返回数组后添加
as const
,或者在useMemo
调用中添加显式类型参数。或