ホームページ  >  記事  >  ウェブフロントエンド  >  React でリアルタイム通知センターを構築する

React でリアルタイム通知センターを構築する

PHPz
PHPzオリジナル
2024-08-24 11:14:02464ブラウズ

Building a Real-Time Notification Center in React

通知により、ユーザーは常に情報を入手し、関心を持ち続けることができます。カスタム React 通知センターを使用すると、ユーザー エクスペリエンスを完全に制御および調整できます。これは、リアルタイム更新のためのフロントエンド コンポーネントとバックエンド コンポーネントの両方をカバーする、ゼロから構築するための簡潔なガイドです。

1. React 通知センターの要件

  • リアルタイム更新: 通知は更新せずに即座に表示されます。
  • バックグラウンド通知: アプリがフォーカスされていないときでも、Service Worker を使用して通知を処理します。
  • マルチチャネルのサポート: アプリ内通知、プッシュ通知、メール、SMS が含まれます。
  • ユーザー設定: ユーザーが通知設定をカスタマイズできるようにします。
  • スケーラビリティ: システムが大量の通知を処理できることを確認します。
  • 信頼性: 通知は正確かつ迅速に配信される必要があります。

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.通知フィードの設計

  • 通知リスト: 既読または削除としてマークするオプションを含むすべての通知を表示します。
  • 通知バッジ: 未読通知数を表示します。
  • トースト通知: 簡単な通知には、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 を使用したトースト通知

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 で通知システムを最初から構築する必要がありますが、上司が早急に通知システムを必要としていて、休暇の計画がある場合 (または本当に休暇が必要な場合)、私の記事をチェックしてください。道具。すべてが簡素化され、すべての一般的な SDK で利用可能な新しい通知 API としてすぐに使用できるコンポーネントが提供されます。私たちがインフラを処理している間、あなたはくつろぐことができます。 ??

以上がReact でリアルタイム通知センターを構築するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。