Переглянути джерело

ToastProvider优化(当组件中的useEffect依赖showToast时,其他组件中调用showToast会触发前者的useEffect)

fogwind 1 тиждень тому
батько
коміт
ddae37d2b8
1 змінених файлів з 9 додано та 8 видалено
  1. 9 8
      src/providers/ToastProvider.tsx

+ 9 - 8
src/providers/ToastProvider.tsx

@@ -1,5 +1,5 @@
 "use client";
-import { ReactNode, createContext, useContext, useState } from "react";
+import { ReactNode, createContext, useContext, useState, useCallback } from "react";
 import { ToastContainer } from "@/components/theme/toast/ToastContainer";
 
 export type ToastType = "success" | "danger" | "warning" | "primary";
@@ -22,9 +22,12 @@ const ToastContext = createContext<ToastContextType | undefined>(undefined);
 export const ToastProvider = ({ children }: { children: ReactNode }) => {
   const [toasts, setToasts] = useState<ToastDataType[]>([]);
 
-  const addToast = (toast: Omit<ToastDataType, "id">) => {
-    // eslint-disable-next-line react-hooks/purity
-    const id = Math.random().toString(36).substr(2, 9);
+  const removeToast = useCallback((id: string) => {
+    setToasts((prev) => prev.filter((toast) => toast.id !== id));
+  },[]);
+  const addToast = useCallback((toast: Omit<ToastDataType, "id">) => {
+
+    const id = crypto.randomUUID();
     const newToast = { id, ...toast };
 
     setToasts((prev) => [...prev, newToast]);
@@ -32,11 +35,9 @@ export const ToastProvider = ({ children }: { children: ReactNode }) => {
     setTimeout(() => {
       removeToast(id);
     }, toast.duration || 5000);
-  };
+  },[removeToast]);
 
-  const removeToast = (id: string) => {
-    setToasts((prev) => prev.filter((toast) => toast.id !== id));
-  };
+  
 
   return (
     <ToastContext.Provider value={{ toasts, addToast, removeToast }}>