繁体   English   中英

React context.provider不会更改默认值

[英]React context.provider doesn't change the default value

我正在使用反应上下文。 首先,我给上下文默认值,然后给Context.Provider不同的值。 但消费者仍然获得默认值

传递通知的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;

消费者


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;


我仍然得到“默认”字符串而不是“值”

您对提供者的价值应该是一个对象,

const value = {
 name: "kim"
}
 <NotificationContext.Provider value={value}>
  <WrappedComponent {...this.props as T} />
 </NotificationContext.Provider>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM