1

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

用户操作 1 - 用户可以单击总数以展开并查看所有的 toasts。到目前为止,我已经为我工作了一切。

用户操作 2 - 如果用户再次单击 toast 的总数,则隐藏其余的 toast 并返回一次只显示 2 个 toast。这对我不起作用。一旦我能做到这一点,那么我当然还想再次展示用户操作 1 中提到的所有 toast。

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}
        />
    </>);
}

这是显示 toast 的组件。

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, maxToast, displayAllNotification]);

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


export default Notification;
4

0 回答 0