簡體   English   中英

如何從我的代碼 React.js/Next.js 制作一個鈎子?

[英]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 ,這很可能是你想要的。

問題是你從你的鈎子返回一個字符串/對象,然后試圖將它作為一個函數調用。

小改動,我建議:

  1. 你應該從你的鈎子中返回一個字符串。 返回 asPath 而不是對象。
    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)}
        />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM