NextJS组件淡化已删除组件

k5hmc34c  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(147)

因此,我使用NextJS和tailwind为我的应用创建了一个通知提供程序,但当我显示多个通知时,最上面的一个被删除,下面的一个接管了它的淡入度值,我该如何解决这个问题?

import { createContext, useState, useContext } from "react";

const Context = createContext();

const Provider = ({ children }) => {
    const [notifications, setNotifications] = useState([]);

    const exposed = {
        addNotification: (type, text, autoClose) => {
            const id = Math.random()
            setNotifications(notifications => [...notifications, { id, type, text, autoClose, fade: false }]);
            if (autoClose) {
                setTimeout(() => {
                    removeNotification(id);
                }, 5000);
            }
        },
    };

    const removeNotification = (id) => {
        setNotifications(notifications => notifications.map(n => n.id === id ? { ...n, fade: true } : n));
        setTimeout(() => {
            setNotifications(notifications => notifications.filter(n => n.id !== id));
        }, 1000);
    }

    return (
        <Context.Provider value={exposed}>
            {children}
            {notifications.length > 0 ? <div className="z-50 fixed top-5 right-5 text-right">
                {notifications.map((notification, index) => {
                    switch (notification.type) {
                        case 'info':
                            return <Info text={notification.text} key={index} remove={() => removeNotification(notification.id)} fade={notification.fade} />
                        /* other cases */
                    }
                })}
            </div> : null}
        </Context.Provider>
    );
}

function Info({ remove, text, fade }) {
    return (
        <div className={`flex items-center w-fit mt-2 mr-0 ml-auto transition-opacity ease-in duration-1000 ${!fade?'opacity-100':'opacity-0'}`}>
            {/* content */}
        </div>
    )
}

export const useProvider = () => useContext(Context);

export default Provider;
mzsu5hc0

mzsu5hc01#

可能还有其他问题需要解决,但是对于具有动态更改项的列表,请考虑避免使用index作为唯一键,以防止列表更改时可能发生的冲突。
也许可以尝试在发布的示例中使用notification.id作为键:

<Context.Provider value={exposed}>
  {children}
  {notifications.length > 0 ? (
    <div className="z-50 fixed top-5 right-5 text-right">
      {notifications.map((notification, index) => {
        switch (notification.type) {
          case "info":
            return (
              <Info
                text={notification.text}
                // 👇 Use id as unique keys
                key={notification.id}
                remove={() => removeNotification(notification.id)}
                fade={notification.fade}
              />
            );
          /* other cases */
        }
      })}
    </div>
  ) : null}
</Context.Provider>

相关问题