首页 > 解决方案 > 状态未更新 redux

问题描述

所以我用 react 和 redux 做了一个通知系统,并添加了一个队列系统来防止同时显示很多通知。它按应有的方式工作,但只有一个问题。如果添加 5 个通知,则第 5 个通知应该进入队列数组,但组件不会说明队列数组现在的长度为 1。如果我再放 5 个通知,我在活动数组上有 4 个,然后在队列数组中有 2 个通知,从这里它知道队列数组长度现在是 2。这是为什么?重新渲染有问题吗?

我的代码:

  const notify = useSelector((state) => state.notify);

  const handleClick = () => {
    let notification = {
      iconType: 0,
      title: 'notification.title',
      message: 'notification.message',
      color: '03A65A',
      width: 0,
    };

    showNotifications(notification);
  };

  const timeoutNotification = async (notification: any) => {
    await dispatch(AddActiveItem(notification));
    setTimeout(async () => {
      await dispatch(RemoveActiveItem(notification.id));
      if (notify.queue.length && notify.active.length < 4) {
        let newQueue = notify.queue;
        let pushItem = newQueue.shift();
        await dispatch(SetNewQueue(newQueue));
        timeoutNotification(pushItem);
      }
    }, 120 * notification.message.length);
  };

  const showNotifications = async (notification: any) => {
    notification = {
      id: notify.id,
      iconType: notification.iconType,
      title: notification.title,
      message: notification.message,
      color: notification.color,
      width: notification.width,
    };

    let newId = notify.id + 1;
    dispatch(SetId(newId));

    if (notify.active.length > 3) {
      await dispatch(AddQueueItem(notification));
    } else {
      timeoutNotification(notification);
    }
  };

标签: reactjsredux

解决方案


请记住,Reduxdispatch是一个异步函数,因此对 Redux 状态所做的更改不会立即可见。如果您确定状态应该/将更新,只需等待更改..


推荐阅读