防止重复 toast Chakra UI

en4*_*4no 5 chakra-ui

我用来chakra防止通知显示(如果它们已经显示了此内容)

\n

但现在我将通知分离到另一个组件中:

\n
import React from \'react\';\nimport { createStandaloneToast } from \'@chakra-ui/react\';\nimport theme from \'../theme\';\n    \nconst Notification = (title, description, status) => {\n    const toast = createStandaloneToast({ theme: theme });\n\n    toast({\n        title: title,\n        description: description,\n        status: status,\n        duration: 3000,\n        position: \'bottom-right\',\n        isClosable: true,\n      });\n\n    return <></>;\n};\n\nexport default Notification;\n
Run Code Online (Sandbox Code Playgroud)\n

在我的组件中,我按如下方式使用它:

\n
import React, { useContext } from \'react\';\n...\n\nconst RemoveToDo = () => {\n    const remove = () => {\n        ...\n        Notification(\'Tarea eliminada.\', \'Has eliminado la tarea.\', \'success\');\n    };\n};\n
Run Code Online (Sandbox Code Playgroud)\n

现在你怎样才能防止它们重复呢?

\n

当我使用时useToast,我在另一个组件中没有单独的通知,我可以通过以下方式防止它们重复:

\n
const id = 2;\nif (!toast.isActive(id)) {\n    toast({\n        id: 2,\n        title: \'Error al crear la tarea.\',\n        description: \'Ya tienes una tarea con esa descripci\xc3\xb3n.\',\n        status: \'warning\',\n        duration: 3000,\n        position: \'bottom-right\',\n        isClosable: true,\n    });\n};\n
Run Code Online (Sandbox Code Playgroud)\n

小智 0

谢谢你的问题。我还使用 chakra UI 并使用 toast 。我认为有两个选择:第一个:创建一个对象,第二个:创建一个高阶函数。我更喜欢第一个...因为第二个使用打字稿会更复杂。这是我的解决方案:

const defaultToastProps = {
 position: "top-right" as ToastPosition,
 duration: 2000,
 isClosable: true,
};

const submitHandler = () => {
 Axios.post("/user/register", formData)
   .then((res) => {
     console.log(res);
     toast({
       title: "Account created.",
       description: "We've created your account for you.",
       status: "success",
       ...defaultToastProps,
     });
     nav("/login");
   })
   .catch((err) => {
     if (err.response) {
       console.log(err.response.data.message);
       toast({
         title: "Something went wrong.",
         description: err.response.data.message,
         status: "error",
         ...defaultToastProps,
       });
     } else {
       console.log(err);
       toast({
         title: "Something went wrong.",
         description: "server-error",
         status: "error",
         ...defaultToastProps,
       });
     }
   });
};
Run Code Online (Sandbox Code Playgroud)