[英]React context.provider doesn't change the default value
I'm using react context. 我正在使用反应上下文。 First I give to the context default value, and then I give to Context.Provider different value.
首先,我给上下文默认值,然后给Context.Provider不同的值。 but the consumer still get the default value
但消费者仍然获得默认值
HOC that pass notifications (for now is just a simple string) 传递通知的HOC(目前只是一个简单的字符串)
export const NotificationContext = React.createContext<string>('default');
function withNotifications<T>(WrappedComponent: React.ComponentType<T>) {
return class ComponentWithTheme extends React.Component<T, { data: any }> {
public render() {
return (
<NotificationContext.Provider value={'value'}>
<WrappedComponent {...this.props as T} />
</NotificationContext.Provider>
);
}
};
}
export default withNotifications;
Consumer 消费者
const Topbar: React.FC<TopbarProps> = props => {
//const [isNotificationOpen, setIsNotificationOpen] = useState(false);
//const [unreadCount, setUnreadCount] = useState(0);
const notificationContext = useContext(NotificationContext);
useEffect(() => {
console.log(notificationContext);
}, Object.values(notificationContext));
console.log(notificationContext);
return (
<div>topBar</div> );
};
export default Topbar;
I'm still get the "default" string and not the "value" 我仍然得到“默认”字符串而不是“值”
Your value to the provider should be an object, 您对提供者的价值应该是一个对象,
const value = {
name: "kim"
}
<NotificationContext.Provider value={value}>
<WrappedComponent {...this.props as T} />
</NotificationContext.Provider>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.