如何利用全局状态统一管理React项目中的Mantine通知
统一管理Mantine通知的方案
针对你遇到的逐个修改组件添加静音判断的冗余问题,可以通过封装全局通知管理工具的方式统一处理规则,避免重复代码,后续新增业务也无需重复修改。以下是两种实用方案:
方案1:封装自定义Hook(组件内使用首选)
把静音判断和Mantine通知的调用逻辑封装到自定义Hook中,组件直接使用这个Hook提供的方法即可:
// hooks/useNotification.ts import { useGlobalState } from '../path-to-your-global-state'; import { notifications } from '@mantine/notifications'; export const useNotification = () => { const { muteMode } = useGlobalState(state => state); // 统一封装show方法,内置静音判断 const show = (config) => { if (!muteMode) { notifications.show(config); } }; // 按需暴露Mantine通知的其他原生方法 return { show, update: notifications.update, clear: notifications.clear, clearAll: notifications.clearAll, }; };
组件中的使用示例:
const A = () => { const notification = useNotification(); useEffect(() => { notification.show({ title: '通知标题', message: '通知内容' // 其他配置 }); }, []); return <>A组件</>; }; // B、C组件完全同理,只需调用notification.show,无需再处理静音逻辑
方案2:全局单例管理器(支持组件外调用)
如果需要在组件外部(比如API请求拦截器、工具函数)调用通知,可以用单例模式结合全局状态订阅,实现全场景的统一管理:
// utils/notificationManager.ts import { notifications } from '@mantine/notifications'; import { globalState } from '../path-to-your-global-state'; class NotificationManager { #muteMode = false; constructor() { // 订阅全局状态,自动同步静音模式 globalState.subscribe(state => { this.#muteMode = state.muteMode; }); } show(config) { if (!this.#muteMode) { notifications.show(config); } } // 直接复用Mantine的原生方法 update = notifications.update; clear = notifications.clear; clearAll = notifications.clearAll; } // 导出单例,全局唯一实例 export const notificationManager = new NotificationManager();
组件内/外的使用示例:
// 组件内使用 const A = () => { useEffect(() => { notificationManager.show({ // 通知配置 }); }, []); return <>A组件</>; }; // 组件外(比如API工具)使用 const fetchData = async () => { try { // 请求逻辑 } catch (error) { notificationManager.show({ title: '请求失败', message: error.message, color: 'red' }); } };
方案优势
- 统一维护:后续如果需要修改通知规则(比如新增通知频率限制、自定义全局样式),只需修改封装层,所有调用处自动生效。
- 减少冗余:组件无需重复编写静音判断逻辑,降低出错概率。
- 扩展性强:可以根据需求在封装层添加更多自定义逻辑,比如日志记录、通知分类控制等。
内容的提问来源于stack exchange,提问作者Eve-Sama
相关产品推荐
相关产品推荐

