英文:
how to type useSearchParams hook when passing it to props or function argument?
问题
在我的组件中,我使用了useSearchParams
钩子,但当我将该钩子传递给props或函数参数时,无法为参数添加类型。
import { useSearchParams } from 'react-router-dom';
const urlSearchParamState = useSearchParams();
const [searchParams, setSearchParams] = urlSearchParamState;
如何从该钩子中导入类型?
export declare function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams];
英文:
I use useSearchParams hook in my component
when i pass hook to props or function argument i can't type parameters
import { useSearchParams } from 'react-router-dom';
const urlSearchParamState = useSearchParams();
const [searchParams, setSearchParams] = urlSearchParamState;
How to import types from hook?
export declare function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams];
答案1
得分: 0
URLSearchParams
已存在作为内置对象。要获取setter,我们可以使用ReturnType
并访问返回的元组的第二个元素:
type SetURLSearchParams = ReturnType<typeof useSearchParams>[1];
英文:
URLSearchParams
already exists as a built-in. To get the setter, we can use ReturnType
and access the second element of the returned tuple:
type SetURLSearchParams = ReturnType<typeof useSearchParams>[1];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论