我有一个简单的react钩子,它返回一个函数.我希望此函数只接受传递到挂钩中的数组中的值.
钩子在这里:
type Options<P> = {
pathname: string;
rootPath: string;
paths: P;
};
export const useLayoutPaths = <P extends string[]>(options: Options<P>) => {
const { pathname, rootPath, paths } = options;
if (paths.length === 0) {
throw new Error("paths must be a non-empty array.");
}
const currentPath = pathname.substring(pathname.lastIndexOf("/") + 1);
const value = paths.includes(currentPath) ? currentPath : paths[0];
const getPath = (name: typeof paths[number]): string =>
`${rootPath}/${String(name)}`;
return { value, getPath };
};
我希望getPath函数只允许"paths"变量中存在的值.
以下是我目前的用法:
const { value, getPath } = useLayoutPaths({
pathname,
rootPath: `/department/${orgId}`,
paths: ["trends", "comments"],
});
console.log(getPath("trends")) <-- Only allow "trends" or "comments"