reactjs - 状态未更新 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);
}
};
解决方案
请记住,Reduxdispatch
是一个异步函数,因此对 Redux 状态所做的更改不会立即可见。如果您确定状态应该/将更新,只需等待更改..
推荐阅读
- html - 动画位置变化而不定义关键帧
- swift - UINavigationBar 的标题不会随着 push segue 的转换而改变
- javascript - 生成两个十进制数之间的随机数
- c++ - 如何在头文件中声明相同类类型的数组?
- python - 如何跳过特定标签中的文本?
- android - Android 创建具有 3 个圆角和 1 个直角的 ImageView
- angular - 用对象数组填充文本数组和值
- python-3.x - 如何使用 python 生成器递归地生成对象?
- javascript - 有没有办法在 CRUD 操作后立即触发更新视图
- ios - Swift - 点击状态栏时 UITableView 没有完成滚动