[英]How to make a hook from my code React.js/Next.js?
我尝试从我的代码中制作一个钩子,但我遇到了问题。 我来自钩子文件的代码:
import { useRouter } from "next/router";
const useCurrentPath = () => {
const { asPath, locale, defaultLocale } = useRouter();
if (locale === defaultLocale) return { asPath };
return `/${locale}${asPath}`;
};
export default useCurrentPath;
我叫它的地方
import { SubHeaderLink, SubHeaderLinks } from "@/components/layout/subHeader/SubHeader";
import { ReactStoryblokComponent, StoryblokLink } from "@/types/storyblok";
import { useStoryblokLinkParser } from "storyblok/useStoryblokLinkParser";
import useCurrentPath from "hooks/useCurrentPath";
type Blok = {
subHeaderLinks: { _uid: string; linkName: string; href: StoryblokLink }[];
};
const StoryblokSubHeader: ReactStoryblokComponent<Blok> = ({
blok: { subHeaderLinks },
}) => {
const { getHref } = useStoryblokLinkParser();
const getCurrentPath = useCurrentPath();
return (
<SubHeaderLinks>
{subHeaderLinks.map(({ _uid, href, linkName }) => (
<SubHeaderLink
key={_uid}
href={getHref(href)}
name={linkName}
isActive={ getCurrentPath() === getHref(href)}
/>
))}
))
</SubHeaderLinks>
);
};
export default StoryblokSubHeader;
在行上
isActive={ getCurrentPath() === getHref(href)}
我遇到了问题“此表达式不可调用。'string | { asPath: string; }' 类型的成分均不可调用。”
const { asPath, locale, defaultLocale } = useRouter();
if (locale === defaultLocale) return { asPath };
您正在从useRouter();
解构asPath
; 在第一行,然后你在第二行将它返回到一个对象中。
尝试:
const { asPath, locale, defaultLocale } = useRouter();
if (locale === defaultLocale) return asPath;
无论如何,您的函数都应该返回一个字符串。
以下行:
const getCurrentPath = useCurrentPath();
将调用useCurrentPath
的结果分配给getCurrentPath
常量。 根据您的钩子,该结果是string
或类型为{ asPath: string }
的对象。
该结果不是函数,因此不可调用。 你在 JSX 中调用它——在<SubHeaderLink />
的isActive
属性中)。
你可能的意思是:
const getCurrentPath = useCurrentPath
,因为useCurrentPath
是可调用的。 或者,或者:
const getCurrentPath = () => useCurrentPath()
另一个问题是您并不总是从自定义挂钩返回string
。
我相信你应该在你的钩子里用return asPath
替换return { asPath }
,所以钩子总是返回一个string
,这很可能是你想要的。
问题是你从你的钩子返回一个字符串/对象,然后试图将它作为一个函数调用。
小改动,我建议:
import { useRouter } from "next/router";
const useCurrentPath = () => {
const { asPath, locale, defaultLocale } = useRouter();
if (locale === defaultLocale) return asPath;
return `/${locale}${asPath}`;
};
export default useCurrentPath;
<SubHeaderLink
key={_uid}
href={getHref(href)}
name={linkName}
isActive={ getCurrentPath === getHref(href)}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.