javascript - 为什么我需要使用 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;
}
解决方案
推荐阅读
- javascript - 如何在 Javascript 中使用嵌套对象?
- javascript - Stripe 客户端集成在第一次点击事件后不会重定向
- html - 设置固定背景全尺寸 html 不起作用
- python - 我如何将分数 1&2 写入 python 中的文本文件?
- git - 作曲家需要在 gitlab 上为 api/v3 而不是 api/v4 请求的 package_name
- python - pip 安装因 ImportError 失败:无法导入名称“SourceDistribution”
- sql - 查询以检查 SQLServer 2008 中表(非索引)的分区
- ruby-on-rails - Rails自动保存不保存对关联的更改
- apk - 为什么dex2jar会产生50个相同的错误
- c# - 在 DataGridView 末尾添加空白行以添加值 c#