在重新加载页面之前永久删除项目

问题描述 投票:0回答:1

如何永久删除通知。

import React, { useEffect, useState, useRef } from 'react';
import { IoMdNotificationsOutline } from "react-icons/io";
import './notif.css';
import { getDocs, collection } from "firebase/firestore";
import { database } from "../config/firebase";
import { MdCancel } from "react-icons/md";

const NotificationComponent = () => {
  const [productList, setProductList] = useState([]);
  const productCollectionRef = collection(database, "singleProduct");

  async function getProductList() {
    try {
      const data = await getDocs(productCollectionRef);
      const filteredData = data.docs.map((doc) => ({
        ...doc.data(),
        id: doc.id
      }));
      setProductList(filteredData.reverse());
    } catch (err) {
      console.error(err);
    }
  };

  useEffect(() => {
    getProductList();
  }, []);

  const [showNotifications, setShowNotifications] = useState(false);
  const [notifications, setNotifications] = useState([]);

  const [currentDate, setCurrentDate] = useState(new Date());
  const [counter, setCounter] = useState(0);
  const currentDateRef = useRef(currentDate);

  useEffect(() => {
    currentDateRef.current = currentDate; // Update currentDateRef when currentDate changes
  }, [currentDate]);

  const toggleNotifications = () => {
    setShowNotifications(!showNotifications);
    if (showNotifications) {
      setCounter(0); // Reset the counter if showNotifications is true
    }
  };

  function isWithinOneWeek(date) {
    const targetDate = new Date(date);
    const checkWeekAhead = new Date();
    checkWeekAhead.setDate(checkWeekAhead.getDate() + 7);

    return Math.abs(targetDate.getTime() - checkWeekAhead.getTime()) <= 7 * 24 * 60 * 60 * 1000;
  }

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentDate(new Date());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    const newNotifications = [];
    productList.forEach(product => {
      if (isWithinOneWeek(new Date(product.expirationDate.seconds * 1000))) {
        newNotifications.push({
          id: product.id,
          message: (
            <div className='notificationMessage'>
              <p>The Product: {product.productName} will be expired in one week</p>
              <p>Product Identifier: {product.uniqueIdentifier}{product.serialNum}</p>
              <p> {new Date(product.expirationDate.seconds * 1000).toLocaleDateString()}</p>
            </div>
          )
        });
      } else if (currentDateRef.current >= new Date(product.expirationDate.seconds * 1000)) {
        newNotifications.push({
          id: product.id,
          message: (
            <div className='notificationMessage'>
              <p>The Product: {product.productName} is expired.</p>
              <p>Product Identifier: {product.uniqueIdentifier}{product.serialNum}</p>
              <p> {new Date(product.expirationDate.seconds * 1000).toLocaleDateString()}</p>
            </div>
          )
        });
      }
    });
    setNotifications(newNotifications);
    setCounter(newNotifications.length);
    console.log(newNotifications);
  }, [productList]);

  // Function to delete a specific notification
  const handleDelete = (id) => {
    const updatedNotifications = notifications.filter(notification => notification.id !== id);
    setNotifications(updatedNotifications);
    setCounter(updatedNotifications.length);
    console.log(updatedNotifications);
  };

  return (
    <div className="notification-component">
      <div><h1>{currentDate.toLocaleDateString()}</h1></div>
      <div className="notification-icon" onClick={toggleNotifications}>
        <IoMdNotificationsOutline className='icon' />
        {showNotifications ? null : counter > 0 && (
          <span className="notification-counter">
            {counter}
          </span>
        )}
      </div>
      {showNotifications && (
        <div className="notification-list">
          <h3>Notifications</h3>
          <ul>
            {notifications.map(notification => (
              <li key={notification.id}>
                {notification.message}
                <span className='deleteNotif' onClick={() => handleDelete(notification.id)}>
                  <MdCancel />
                </span>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
};

export default NotificationComponent;

重新加载页面后,它不断重新出现。我希望它在页面上删除它。例如,有 6 个通知 newNotifications 数组是 [6],我删除了一个特定的通知,在 console.log 后,该数组变成了 [5]。但是当我重新加载页面后,newNotification数组又变成了[6]。我想要它,这样它就不会重新出现在页面中。我是网页设计新手。

reactjs react-hooks notifications delete-file
1个回答
0
投票

这里我们需要区分前端和后端。您的 React 应用程序是您的前端,Firestore 是您的后端。

您正在做的是从 React 中删除通知,只要应用程序正在运行,这就会起作用,但是当您刷新页面时,React 应用程序将“重新启动”,并且仅对 React 所做的所有状态更改都将丢失。 React 中的任何状态都无法在刷新期间持久化。

如果您想保留状态更改,则需要将其存储在后端,在本例中为 Firestore 数据库。根据您的需要,有多种方法可以做到这一点,但最简单的方法可能是在产品中添加一个字段来告知通知是否已被删除。

© www.soinside.com 2019 - 2024. All rights reserved.