通知讓使用者了解狀況並參與其中。自訂 React 通知中心可讓您完全控制和自訂使用者體驗。這是從頭開始建立一個簡明指南,涵蓋用於即時更新的前端和後端元件。
前端
後端
Microservice | Functionality |
---|---|
Notification Service | Generates and stores notifications |
Dispatch Service | Sends notifications to different channels |
User Preferences Service | Manages user settings and preferences |
範例: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'); });
範例:帶有 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;
範例: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;
範例:註冊 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); }); }
範例:顯示通知
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' }); } }); }
範例:在 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));
範例:通知清單元件
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();
範例:使用 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中文網其他相關文章!