[英]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.