簡體   English   中英

錯誤:有條件地調用 React Hook “useCallback”。 在每個組件渲染中,必須以完全相同的順序調用 React Hooks

[英]Error: React Hook "useCallback" is called conditionally. React Hooks must be called in the exact same order in every component render

獲取構建錯誤使用有條件調用的回調鈎子。 如果我不使用 useCallback 我得到錯誤 JSX props should not use arrow functions
const LinkComp = <T extends {}>(props: LinkProps & T extends AnchorProps? AnchorProps: ButtonProps) => { const { title, hideTitle, children, url = '', action, label, newWindow, class, isName inheritColor = true, underlineOnHover = true, underline = false, theme = '', bold = false, onClick, modal = false, forceAnchorTag = false, appendQueryParams = true, showOutline = true, ...linkProps } = props; const [handleClick] = useRouter(action, url); 常量 forwardedParams = useSelector(selectForwardedQueryParams);

const linkContent = (
    <>
        {iconName && <Icon name={iconName} className='mr-3' />}
        {!hideTitle && (title || children)}
    </>
);

if (modal) {
    if (linkProps.modalTitle) delete linkProps.modalTitle;

    return (
        <button {...(anchorProps as ButtonProps)} role='link' onClick={onClick as ButtonProps['onClick']}>
            {linkContent}
        </button>
    );
}

// queryString.stringifyUrl combines the params from both url and forwarded params.
// don't append the params for `tel` links
const forwardedParamsUrl = queryString.stringifyUrl({ url, query: !url?.includes('tel:') && forwardedParams });

const handleAnchorClick = useCallback((e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) =>  {
    if (handleClick) handleClick(e);
    
    return true;
},[handleClick]);

if (forceAnchorTag) {
    return (
        <a href={forwardedParamsUrl} {...(anchorProps as AnchorProps)} onClick={handleAnchorClick}>
            {linkContent}
        </a>
    );
}
// search extras uses the query params in a different way, so no need to append them here
const fullUrl = appendQueryParams ? forwardedParamsUrl : url;

return (
    <Link href={fullUrl} passHref={isExternal || newWindow}>
        <a {...(anchorProps as AnchorProps)} onClick={handleClick}>
            {linkContent}
        </a>
    </Link>
);

};

導出默認 LinkComp;

您不應該將 function 傳遞給 useCallback 掛鈎。 你為什么這樣做?

暫無
暫無

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

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