1.父组件引用
import WebsocketProvider from "./WebsocketProvider";

2.provider 组件封装
import React, { useContext, useEffect, useState } from "react";
import { notification } from "antd";
import closeImg from "@assets/images/home/closeIcon.png";
import newOrderIcon from "@assets/images/home/newOrderIcon.png";
import { UserContext } from "@src/auth/index";
let websocket,
lockReconnect = false;
let retryCount = 0;
interface WebsocketProps {
children: React.ReactNode;
}
let updateOrderNumberTimer = null
const WebsocketProvider: React.FC<WebsocketProps> = ({ children }) => {
const { Provider } = React.createContext();
const bLanguage = localStorage.getItem("bLanguage");
const isEn = bLanguage === "en";
let wsBaseUrl = "";
let openFlag = false;
let initFlag = "init";
if (process.env.DEPLOY_ENV === "prod") {
wsBaseUrl = "wss://gows-api.funpinpin.com";
} else if (process.env.DEPLOY_ENV === "staging") {
wsBaseUrl = "wss://go-ws-api.staging.funpinpin.top";
} else {
wsBaseUrl = "wss://go-ws-api.test.funpinpin.top";
}
const wsUrl = `${wsBaseUrl}/ws?domain=${localStorage.getItem("shopDomain") ||
window.location.hostname}`;
useEffect(() => {
initFlag = "no_init";
createWebSocket(wsUrl);
}, []);
useEffect(() => {
if (
document.getElementsByClassName("new-order-notification").length > 0 &&
initFlag !== "init"
) {
notification.open({
className: "new-order-notification",
message: "",
placement: "bottomRight",
bottom: 50,
duration: null,
description: notitionMessage(),
key: "initKey"
});
}
}, [bLanguage]);
const notitionMessage = () => {
return (
<div className="flex flex-space-between">
<div>
<img
width={16}
style={{ marginRight: "8px" }}
src={newOrderIcon}
alt=""
/>
<span
onClick={() => {
// history.push("/orders");
}}
>
{isEn ? "New order for you" : "您有新订单"}
</span>
</div>
<img
width={10}
onClick={() => {
notification.close("initKey");
openFlag = false;
}}
style={{ cursor: "pointer" }}
src={closeImg}
alt=""
/>
</div>
);
};
const openNotification = () => {
openFlag = true;
if (openFlag) {
notification.open({
className: "new-order-notification",
message: "",
placement: "bottomRight",
bottom: 50,
duration: null,
description: notitionMessage(),
key: "initKey"
});
}
};
const createWebSocket = wsUrl => {
retryCount++;
websocket = new WebSocket(wsUrl);
websocket.onopen = function() {
heartCheck.reset().start();
};
websocket.onerror = function() {
reconnect(wsUrl);
};
websocket.onclose = function() {
reconnect(wsUrl);
};
websocket.onmessage = function(e) {
lockReconnect = true;
retryCount = 0;
try {
let data = JSON.parse(e.data);
if (data?.id === 22) {
if (!openFlag) {
openNotification();
}
}
} catch (e) {
return false;
}
};
};
const reconnect = wsUrl => {
if (retryCount > 5) return;
setTimeout(function() {
createWebSocket(wsUrl);
lockReconnect = false;
}, 4000);
};
const heartCheck = {
timeout: 30000,
timeoutObj: null,
serverTimeoutObj: null,
reset: function() {
clearInterval(this.timeoutObj);
return this;
},
start: function() {
this.timeoutObj = setInterval(function() {
if (websocket?.readyState === 1) {
websocket?.send("ping");
}
}, this.timeout);
}
};
const closeWebSocket = () => {
websocket?.close();
};
return <Provider value={{}}>{children}</Provider>;
};
export default WebsocketProvider;