首页 > 解决方案 > 为什么我需要使用 react 和 javascript 专门检查 false?

问题描述

我只想在条件 1 或条件 2 为真时呈现 div 元素。

下面是我的代码。

const Parent = () => {
    const {notify} = useNotification();
    return (
        <SomeComponent 
            notify ({
                actions: showInfo(item),
            });
        />
    );
}

const showInfo = (item) => {
    return (
        <>
            {condition === 'value1' || condition === 'value2' ?
                <div>header</div>
                : undefined
            }
        </>
    );
}

const useNotifications = () => {
    const [activeNotifications, setActiveNotifications] = React.useContext(NotificationContext);
    const notify = React.useCallback(
        (notifications: Notification | Notification[]) => {
            setActiveNotifications(activeNotifications => [
                 ...activeNotifications,
            ]);
        }
        [setActiveNotifications]
    );
    return notify;
}


const Notification: React.FC<Props> = ({
    description,actions}) => {
        console.log('actions',actions) //here actions is printed false
        return (
            {(description || actions) && ( //why doesnt this condition work
                <Body>//this is displayed even if actions is false
                    {actions && <div> {actions} </div>}
                </Body>
            }
        );
     }
 })

在上面的代码中,即使从控制台日志语句中看到的操作是错误的,也会显示 Body div。

如果我将条件更改为

{(description || actions === true) &&
     <Body>//this is not displayed
         {actions && <div>{actions}</div>}
     </Body>
}

有人可以帮助我理解为什么我必须明确检查 {actions === true} 以及为什么 {actions} 不起作用。谢谢。

EDIT: the type for the action is set like below

export type NotificationProps = {
  actions?: React.ReactNode;
}
    

标签: javascriptreactjs

解决方案


推荐阅读