Antd 通知出现两次?

Emm*_*mma 7 setstate reactjs antd

我正在使用 antd 通知组件,如下所示

        import { notification } from "antd";

        const Notification = ({ msg, type, clearMsg }) => {
          return (
            <div>
              {notification[type]({
                description: msg,
              })}
              {clearMsg()}
            </div>
          );
        };

        export default Notification;
Run Code Online (Sandbox Code Playgroud)

我只是在需要弹出通知的任何地方使用它。例如API响应失败后:

          const onSubmit = async (e) => {
            try {
              const res = await login(data);
              if (res.message) {
                setError({ state: true, msg: res.message });
              }
            } catch (err) {
              console.log(err);
            }
          };
Run Code Online (Sandbox Code Playgroud)

然后根据错误状态,我在返回正文中显示通知,如下所示:

          { error.state ?
            <Notification 
               type="error" 
               msg="some msg" 
               clearMsg={() => setError({state: false, msg: ""})} :
             null
          }
Run Code Online (Sandbox Code Playgroud)

但同时出现两个弹出窗口而不是一个,任何人都可以指导我为什么会出现这种行为吗?

小智 9

notification.destroy();我通过在显示通知之前使用解决了我的问题。下面是一个例子:

const showNotification = () => {
    notification.destroy();
    notification.open({message: 'message here'});
}
Run Code Online (Sandbox Code Playgroud)


小智 4

使用属性分配唯一标识符key。请参阅: https: //ant.design/components/notification/#API

const Notification = ({ key, msg, type, clearMsg }) => {
  return (
    <div>
      {notification[type]({
        key,
        description: msg,
      })}
      {clearMsg()}
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)