首頁  >  文章  >  web前端  >  在 React 中建立即時通知中心

在 React 中建立即時通知中心

PHPz
PHPz原創
2024-08-24 11:14:02464瀏覽

Building a Real-Time Notification Center in React

通知讓使用者了解狀況並參與其中。自訂 React 通知中心可讓您完全控制和自訂使用者體驗。這是從頭開始建立一個簡明指南,涵蓋用於即時更新的前端和後端元件。

1. React 通知中心的要求

  • 即時更新:通知應立即顯示,無需刷新。
  • 後台通知:即使應用程式未處於焦點狀態,也可以使用 Service Worker 來處理通知。
  • 多管道支援:包括應用程式內通知、推播通知、電子郵件和簡訊。
  • 使用者首選項:允許使用者自訂其通知設定。
  • 可擴充性:確保系統可以處理大量通知。
  • 可靠性:通知必須準確、及時地發送。

2. 系統架構概述

前端

  • React App:顯示通知並處理即時更新。
  • Service Worker:透過通知 API 管理後台通知。
  • WebSocket/輪詢:保持通知源即時更新。

後端

  • 微服務
    • 通知服務:產生並儲存通知。
    • 調度服務:向各個管道發送通知。
    • 使用者首選項服務:管理通知的使用者設定。
  • 訊息佇列:高效率處理通知分發。
  • 資料庫:儲存使用者首選項和通知日誌。
  • 推播服務:與 Firebase 和 APN 整合以發送通知。

3. 後端架構

3.1.微服務設計

微服務 功能 標題>
Microservice Functionality
Notification Service Generates and stores notifications
Dispatch Service Sends notifications to different channels
User Preferences Service Manages user settings and preferences
通知服務 產生並儲存通知 派遣服務 向不同管道發送通知 使用者偏好服務 管理使用者設定和首選項 表>

3.2.資料庫設計

  • 通知表:儲存通知元資料。
  • 使用者首選項表:追蹤使用者設定。
  • 日誌表:記錄所有發送的通知。

範例:Node.js/Express 中的通知服務

const express = require('express');
const app = express();

let notifications = [];

app.post('/notify', (req, res) => {
    const notification = {
        id: notifications.length + 1,
        type: req.body.type,
        message: req.body.message,
        userId: req.body.userId,
        status: 'unread',
        timestamp: new Date()
    };

    notifications.push(notification);
    res.status(200).send(notification);
});

app.listen(3000, () => {
    console.log('Notification Service running on port 3000');
});

4. 即時溝通

4.1. WebSocket 連接

  • 伺服器:處理連線並廣播通知。
  • 客戶端:監聽更新並即時更新UI。

範例:帶有 Socket.IO 的 WebSocket 伺服器

const io = require('socket.io')(3001);

io.on('connection', (socket) => {
    console.log('User connected:', socket.id);

    socket.emit('notification', {
        message: 'New notification!',
        timestamp: new Date()
    });

    socket.on('disconnect', () => {
        console.log('User disconnected:', socket.id);
    });
});

React 中的客戶端整合

import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';

const socket = io('http://localhost:3001');

function NotificationCenter() {
    const [notifications, setNotifications] = useState([]);

    useEffect(() => {
        socket.on('notification', (notification) => {
            setNotifications(prev => [...prev, notification]);
        });
    }, []);

    return (
        <div>
            <h2>Notification Center</h2>
            {notifications.map((notif, index) => (
                <div key={index}>{notif.message} - {notif.timestamp}</div>
            ))}
        </div>
    );
}

export default NotificationCenter;

4.2.輪詢作為後備

  • 客戶端:定期檢查伺服器是否有新通知。

範例:React 中的輪詢實作

import React, { useEffect, useState } from 'react';

function NotificationCenter() {
    const [notifications, setNotifications] = useState([]);

    useEffect(() => {
        const interval = setInterval(() => {
            fetch('/api/notifications')
                .then(response => response.json())
                .then(data => setNotifications(data));
        }, 5000); // Poll every 5 seconds

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

    return (
        <div>
            <h2>Notification Center</h2>
            {notifications.map((notif, index) => (
                <div key={index}>{notif.message}</div>
            ))}
        </div>
    );
}

export default NotificationCenter;

5. 整合通知 API 和 Service Worker

5.1.服務人員

  • 註冊:處理後台通知。

範例:註冊 Service Worker

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js').then(registration => {
        console.log('Service Worker registered:', registration.scope);
    }).catch(error => {
        console.error('Service Worker registration failed:', error);
    });
}

5.2.通知API

  • 權限處理:請求顯示通知的權限。
  • 觸發通知:即使應用程式未處於活動狀態也顯示通知。

範例:顯示通知

if (Notification.permission === 'granted') {
    new Notification('New message!', {
        body: 'Click to view the message.',
        icon: '/path/to/icon.png'
    });
} else if (Notification.permission !== 'denied') {
    Notification.requestPermission().then(permission => {
        if (permission === 'granted') {
            new Notification('New message!', {
                body: 'Click to view the message.',
                icon: '/path/to/icon.png'
            });
        }
    });
}

6. 使用 Firebase 和 APN 推播通知

6.1. Firebase 雲端訊息傳遞 (FCM)

  • 設定:註冊 Firebase 並取得令牌。
  • 發送通知:使用令牌發送通知。

範例:在 Node.js 中使用 FCM 發送推播通知

const admin = require('firebase-admin');
const serviceAccount = require('./path/to/serviceAccountKey.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

const message = {
    notification: {
        title: 'New Notification',
        body: 'You have a new notification!'
    },
    token: 'device-token'
};

admin.messaging().send(message)
    .then(response => console.log('Message sent:', response))
    .catch(error => console.error('Error sending message:', error));

6.2. Apple 推播通知服務 (APN)

  • 整合:處理設備令牌並使用它們透過 APN 發送通知。

7. 在 React 中建立通知中心 UI

7.1.設計通知源

  • 通知清單:顯示所有通知,並帶有標記為已讀或刪除的選項。
  • 通知徽章:顯示未讀通知數。
  • Toast 通知:使用像 React-toastify 這樣的函式庫來取得簡短通知。

範例:通知清單元件

import React from 'react';

function NotificationList({ notifications }) {
    return (
        <div>
            {notifications.map(notification => (
                <div key={notification.id}>{notification.message}</div>
            ))}
        </div>
    );
}

export default NotificationList;

範例:使用 React-toastify 的 Toast 通知

import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

toast.configure();

function notify() {
    toast('New notification!', { position: toast.POSITION.BOTTOM_RIGHT });
}

notify();

7.2.使用 Redux 或 Context API 管理狀態

  • 全域儲存:使用 Redux 或 Context API 全域管理通知。
  • 即時更新:透過 WebSocket 或輪詢使用新通知更新商店。

範例:使用 Redux 管理狀態

import { createSlice } from '@reduxjs/toolkit';

const notificationSlice = createSlice({
    name: 'notifications',
    initialState: [],
    reducers: {
        addNotification: (state, action) => {
            state.push(action.payload);
        },
        markAsRead: (state, action) => {
            const notification = state.find(n => n.id === action.payload);
            if (notification) {
                notification.read = true;
            }
        }
    }
});

export const { addNotification, markAsRead } = notificationSlice.actions;
export default notificationSlice.reducer;

作為一名優秀的開發人員,您應該繼續從頭開始構建React 通知系統,但是,如果您的老闆盡快需要它並且您已經計劃了假期(或者只是真的需要休息),請查看我的工具。它簡化了一切,並為您提供了即用型元件作為新的通知 API,可在所有流行的 SDK 中使用。所以您可以在我們處理基礎設施時放鬆一下! ??

以上是在 React 中建立即時通知中心的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn