我想检查对象是否有一些值,然后渲染组件。
下面是我的代码,
const Parent = () => {
const {notifiy} = useNotifications();
return (
<SomeComponent
notify ({ actions: showInfo(item)})
/>
)
}
const showInfo = (item) => {
return(
<>
{condition === 'value1' || condition === 'value2' ?
<div>header</div>
: undefined
}
</>
);
}
export type NotificationType = 'success' | 'error';
type StyledNotificationProps = { type?:NotificationType} & SpaceProps;
export type Notification = {
actions?: React.ReactNode;
} & StyledNotificationProps & React.HTMLAttributes<HTMLDivElement>;
const useNotifications = () => {
const [activeNotifications, setActiveNotifications] = React.useContext(NotificationContext);
const notify = React.useCallback(
(notifications: Notification | Notification[]) => {
const flatNotification = flatten([notifications]);
console.log('flatNotification', flatNotification);//this contains the
//actions.props.children
console.log('actions.props.children', actions && actions.props.children); //gives error
//props doesnt exist on type string
setActiveNotifications(activeNotifications => [
...activeNotifications,
]);
};
);
return notify;
}
当我记录 flatNotifications 的值时,控制台中的输出如下
flatNotifications [{}]
0
actions:
$$typeof: Symbol(react.element)
key: null
props:
children: undefined //interested in this
__proto__:Object
从上面的对象数组可以看出,我想检查 actions.props.children 是否未定义
当我在 useNotifications 中执行时,我得到类型字符串中不存在道具。
这是因为将通知类型设置为通知 |通知中的通知[] 如果我将它设置为下面的任何内容,它就不会抛出错误。
const notify = React.useCallback(
(notifications: any) => {
const flatNotification = flatten([notifications]);
console.log('flatNotification', flatNotification);//this contains the
//actions.props.children
console.log('actions.props.children', actions && actions.props.children);//doesnt throw
//error
setActiveNotifications(activeNotifications => [
...activeNotifications,
]);
现在的问题是这里的通知类型应该是什么。或者换句话说,我应该如何更改通知类型。
谢谢。