我有一个从 Spring Boot 后端接收通知的屏幕,我将它们显示在一个铃铛中。删除通知时,它会很好地删除它,但是当另一个新通知到达时,它会加载我已经删除的通知。
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
// core components
const HeaderNotificacions = () => {
const [chipData, setChipData] = useState([]); //Hook where I load the notifications that come from the backend >
const historyAlerts = localStorage.getItem('notys')
? JSON.parse(localStorage.getItem('notys'))
: []; if (chipData.length === 0 && historyAlerts.length !== 0) { //I get the notifcations when I reload the browser
setChipData(historyAlerts); }
useEffect(() => {
var sock = new SockJS(
`${process.env.REACT_APP_WEB_SOCKET}mocaConsola/api/notifications`
);
let stompClient = Stomp.over(sock);
sock.onopen = function () {
/* console.log('open'); */
};
stompClient.connect({}, function (frame) {
stompClient.subscribe('/ws/alertNotification', function (greeting) {
if (stompClient !== null) {
stompClient.disconnect();
}
setChipData([
...chipData,
{
key: greeting.headers['message-id'],
label: JSON.parse(greeting.body).content,
},
]);
});
}); }, [chipData]);
localStorage.setItem('notys', JSON.stringify(chipData));
const handleDelete = (chipToDelete) => () => {
const historyAlerts = localStorage.getItem('notys') //function to delete a notification
? JSON.parse(localStorage.getItem('notys'))
: [];
setChipData((chips) =>
chips.filter((chip) => chip.key !== chipToDelete.key)
);
const local = historyAlerts.filter((chip) => chip.key !== chipToDelete.key);
localStorage.setItem('notys', JSON.stringify(local)); };