-1

我有一个从 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));   };
4

1 回答 1

1

其中一个问题可能是您没有断开与套接字的连接,因此第一次订阅(在闭包中具有 chipData 的初始值)将其恢复。取消订阅效果清理可能会有所帮助,类似于:

useEffect(() => {
   
/* your code */      

>     stompClient.connect({}, function (frame) {
>       subscription = stompClient.subscribe('/ws/alertNotification', function (greeting) {
>         if (stompClient !== null) {
>           stompClient.disconnect();
>         }
> 
>         setChipData([
>           ...chipData,
>           {
>             key: greeting.headers['message-id'],
>             label: JSON.parse(greeting.body).content,
>           },
>         ]);
>       });
>     });  
   
   return () => subscription && subscription.unsubscribe();
}, [chipData]);

同样出于性能考虑,我们可以在每次更新chipData时跳过重新创建连接/订阅。我们可以使用setChipData 参数的回调版本,它引用状态的最新值。

setChipData(prevData => [
>           ...prevData,
>           {
>             key: greeting.headers['message-id'],
>             label: JSON.parse(greeting.body).content,
>           },
>         ]);

因此我们可以将 to 替换[chipData][]useEffect 的第二个参数,并且每个组件加载只打开一次连接。

于 2021-03-02T18:21:04.227 回答