【发布时间】:2020-11-03 05:51:21
【问题描述】:
我是 socket.io 的新手,我正在尝试实现一个简单的通知。
我的问题是我执行handleClick 函数将open 转换为真值,而当socket.on 运行其读取错误/open 的默认值时。
Notification.js
const [open, setOpen] = useState(false);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
if (!open) {
setOpen(true) // set open to true
}
};
useEffect(() => {
socket.on("notification", function (data) {
console.log('SOCKET', open) // idk why this is reading false
})
}, [])
编辑
这是我的use-case handleClick func 是用户加载他/她的通知的地方,它将设置open 为真,当socket 运行时,它将检查open 是否为真并将新通知发送到现有的通知数组
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
if (!open) {
setOpen(true) // set open to true
dispatch(getNotifications(params)) // load user notifications
}
};
useEffect(() => {
socket.on("notification", function (data) {
console.log('SOCKET', open) // returning false always
notificationData(data.data)
})
}, [])
const notificationData = ({ sender, message, notif }) => {
setNotifCounter(notifCounter => notifCounter + 1)
setNotification(_.startCase(sender) + ' - ' + message, 'info')
if (open) { // check if user already loaded his/her own notification
dispatch(getNewNotif(notif)) // push to array to avoid duplicate
}
}
【问题讨论】:
标签: javascript node.js reactjs websocket socket.io