因此,我使用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;
1条答案
按热度按时间mzsu5hc01#
可能还有其他问题需要解决,但是对于具有动态更改项的列表,请考虑避免使用
index
作为唯一键,以防止列表更改时可能发生的冲突。也许可以尝试在发布的示例中使用
notification.id
作为键: