以编程方式设置 React-Toastify toast 限制以在 UI 上显示和隐藏 toast 数量

问题描述

我有一个用例,一次可以显示最大数量的toast是2。如果有超过2个toast,那么也会显示toast的总数 在当前显示的 2 个吐司中。

用户操作 1 - 用户可以单击总数以展开并查看所有的 toast。到这部分为止,我已经为我准备好了一切。

用户操作 2 - 如果用户再次点击 Toast 总数,则隐藏其余的 Toast 并返回一次只显示 2 个 Toast。这是什么 不为我工作。一旦我能做到这一点,当然我也想再次展示用户操作 1 中提到的所有吐司。

notificationmanager 组件上,我将maxToast 设置为 2。然后 onClick handleMaxNotification() 会将最大 toast 值更改为 null - 显示所有的 toast(这是有效的) .

handleMaxNotification() 还会切换回 maxToast to 2 并在本地状态上正确设置值,但是 react-toastify 不会在 UI 中反映出来。 例如显示 4 吐司不会返回 2. 非常感谢帮助!

export default function notificationmanager() {
    const [maxToast,setMaxToast] = useState(2); // default
    const [displayAllNotification,setdisplayAllNotification] = useState(false);

    const handleMaxNotification = () => {
        setdisplayAllNotification(v => !v);
    };

    useEffect(() => {
        if (displayAllNotification)
            setMaxToast(null);
        else
            setMaxToast(2);
    },[displayAllNotification]);

    return (<>
        <ToastContainer
            newestOnTop={true}
            limit={maxToast}
        />
        <Notification
            maxToast={maxToast}
            handleMaxNotification={handleMaxNotification}
            displayAllNotification={displayAllNotification}
        />
    </>);
}

这是显示吐司的组件。

import { displayToast } from '../components/toast/displayToast';

const Notification = ({handleMaxNotification,maxToast,displayAllNotification}) => {

    const notifications = useSelector(state => state.notifications);
    const totalNotification = notifications.length > 2 ? notifications.length : ''; 
 
    const Toast = () => (
        <div>
            <span onClick={() => handleMaxNotification()}>{totalNotification}</span>
            <span><Icon name='circle' /></span><span>Notification</span>
        </div>
    );

    const showNotification = (id) => {
        const toastOptions = { toastId: id };
        displayToast(Toast,toastOptions);
    };

    const handleNotification = () => {
        notifications.forEach(({ id }) => showNotification(id));
    };

    useEffect(() => {
        handleNotification();
    },[notifications,displayAllNotification]);

    return (<span></span>);
};


export default Notification;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)