【问题标题】:Antd Notification appearing twice?Antd Notification 出现两次?
【发布时间】:2021-02-24 14:06:08
【问题描述】:

我使用antd通知组件如下

        import { notification } from "antd";

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

        export default Notification;

我只是在需要弹出通知的任何地方使用它。例如 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);
            }
          };

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

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

但同时出现两个弹出窗口而不是一个,谁能指导我为什么会出现这种行为?

【问题讨论】:

  • 为什么不直接从func onSubmit调用notification[type]()?

标签: reactjs antd setstate


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 2020-09-09
    • 2014-01-20
    • 1970-01-01
    相关资源
    最近更新 更多