【问题标题】:Error: React Hook "useCallback" is called conditionally. React Hooks must be called in the exact same order in every component render错误:有条件地调用 React Hook “useCallback”。在每个组件渲染中,必须以完全相同的顺序调用 React Hooks
【发布时间】:2022-01-13 20:17:15
【问题描述】:

使用条件调用的回调钩子获取构建错误。如果我不使用 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,
        className,
        iconName,
        isExternal,
        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);
    const 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>
    );
};

export default LinkComp;

【问题讨论】:

  • 你能把useCallback钩子上面的所有代码都显示出来吗?事实上,那个钩子看起来不错。
  • 您的useCallback 是否在某些条件逻辑中定义?

标签: javascript reactjs react-hooks


【解决方案1】:

您需要将您的useCallback 定义移到if (model) 检查上方。这个if 块可能会导致您的组件在函数被useCallback 记忆之前呈现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2021-03-20
    • 1970-01-01
    • 2019-12-28
    相关资源
    最近更新 更多