我正在使用 Laravel 和 React 开发一个聊天应用程序。我想为传入消息创建通知。通知即将到来,但我收到太多请求错误。
const fetchNotificationMessages = () => {
if (session !== undefined && session.id !== undefined) {
axios.post(Route.get('notifications'), {
user: session.id
}).then(response => {
if (response.data.notification !== undefined) setNotifications(response.data.notification.reverse())
})
}
};
const fetchUnreadMessageCount = () => {
if (session !== undefined && session.id !== undefined) {
axios.post(Route.get('unread-message-count'), {
user: session.id
})
.then(response => {
const count = response.data.count;
setUnreadMessageCount(count);
});
}
};
useEffect(() => {
fetchUnreadMessageCount();
fetchNotificationMessages();
Storage.set('session', session);
}, [session, notifications,unreadMessageCount]);
When I type fetchUnreadmessagecount and fetchNotificationMessage as useEffecte on the NotificationContext page, I get the too many requests error. Thanks in advance for your help.
let's take you are taking state variable as [notifications, setNotifications] =
useState()
if it is like that you have to remove the dependency of notifications from
useEffect 依赖,只有它会导致太多重新渲染。请 提供正确的信息,例如您想要获取通知的时间 警报
const fetchNotificationMessages = () => {
if (session !== undefined && session.id !== undefined) {
axios.post(Route.get('notifications'), {
user: session.id
}).then(response => {
if (response.data.notification !== undefined)
setNotifications(response.data.notification.reverse())
})
}
};
const fetchUnreadMessageCount = () => {
if (session !== undefined && session.id !== undefined) {
axios.post(Route.get('unread-message-count'), {
user: session.id
})
.then(response => {
const count = response.data.count;
setUnreadMessageCount(count);
});
}
};
useEffect(() => {
fetchUnreadMessageCount();
fetchNotificationMessages();
Storage.set('session', session);
}, [session]);