如何从我的代码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,这很可能是你想要的。

问题是你从钩子返回一个字符串/对象,然后试图调用它作为一个函数。

小改动,我建议:

  1. 你应该从钩子返回一个字符串。返回路径而不是对象。
import { useRouter } from "next/router";

const useCurrentPath = () => {
const { asPath, locale, defaultLocale } = useRouter();
if (locale === defaultLocale) return asPath;
return `/${locale}${asPath}`;  
};
export default useCurrentPath; 
  1. 直接使用字符串,而不是试图调用对象/字符串,这是导致错误的原因。
<SubHeaderLink
key={_uid}
href={getHref(href)}
name={linkName}
isActive={ getCurrentPath === getHref(href)}
/>