从 WebSocket React 获取数据
Fetching Data from WebSocket React
我正在从组件中的 Websocket 获取数据:
function Data() {
const [price, setPrice] = useState("");
const [date, setDate] = useState("");
const ws = new WebSocket(
"wss://stream.tradingeconomics.com/?client=guest:guest"
);
const subscription = { topic: "subscribe", to: "EURUSD:CUR" };
const initWebsocket = () => {
ws.onopen = () => {
console.log("Connection Established!");
ws.send(JSON.stringify(subscription));
};
ws.onmessage = (event) => {
const response = JSON.parse(event.data);
setPrice(response.price.toFixed(3));
let today = new Date(response.dt * 1);
const options = {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
};
let date = today.toLocaleDateString("en-EN", options);
setDate(date);
//ws.close();
};
ws.onclose = () => {
console.log("Connection Closed!");
//initWebsocket();
};
ws.onerror = () => {
console.log("WS Error");
};
};
useEffect(() => {
initWebsocket();
// cleanup method which will be called before next execution. in your case unmount.
return () => {
ws.close();
};
}, []);
// useEffect(() => {
// setTimeout(initWebsocket(), 10000);
// }, []);
return (
<div>
Price : {price}
Last Update: {date}
</div>
);
}
export default Data;
关于这个的两个问题:
- 使用此代码,在某些时候我收到资源不足错误,但数据仍在检索...我不知道为什么。
2) 如果我使用注释的 useEffect 除了 setTimeout 之外它仍然从网络套接字获取数据...我怎样才能每 10 秒获取一次数据?
您可以使用 setInterval 运行 定义周期内的代码块。
setInterval(()=>{your function}, 10000)
这只是您上一个问题的答案。如果您想定期 运行 一个代码,setInterval 是您的不二之选。
我在代码沙箱中稍微编辑了你的代码:
import "./styles.css";
import { useState, useEffect } from "react";
export default function App() {
const [price, setPrice] = useState("");
const [date, setDate] = useState("");
const subscription = { topic: "subscribe", to: "EURUSD:CUR" };
useEffect(() => {
const ws = new WebSocket(
"wss://stream.tradingeconomics.com/?client=guest:guest"
);
ws.onopen = () => {
console.log("Connection Established!");
ws.send(JSON.stringify(subscription));
};
ws.onmessage = (event) => {
const response = JSON.parse(event.data);
console.log(response);
if (response.topic === "EURUSD") {
setPrice(response.price.toFixed(3));
let today = new Date(response.dt * 1);
const options = {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric"
};
let date = today.toLocaleDateString("en-EN", options);
setDate(date);
}
//ws.close();
};
ws.onclose = () => {
console.log("Connection Closed!");
//initWebsocket();
};
ws.onerror = () => {
console.log("WS Error");
};
return () => {
ws.close();
};
}, []);
// useEffect(() => {
// setTimeout(initWebsocket(), 10000);
// }, []);
return (
<div>
<p>Price : {price}</p>
<p>Last Update: {date}</p>
</div>
);
}
我所做的,基本上是将整个套接字连接放在 useEffect 中,并为响应设置一个 if 条件。
https://codesandbox.io/embed/dark-fog-msg3v?fontsize=14&hidenavigation=1&theme=dark
我正在从组件中的 Websocket 获取数据:
function Data() {
const [price, setPrice] = useState("");
const [date, setDate] = useState("");
const ws = new WebSocket(
"wss://stream.tradingeconomics.com/?client=guest:guest"
);
const subscription = { topic: "subscribe", to: "EURUSD:CUR" };
const initWebsocket = () => {
ws.onopen = () => {
console.log("Connection Established!");
ws.send(JSON.stringify(subscription));
};
ws.onmessage = (event) => {
const response = JSON.parse(event.data);
setPrice(response.price.toFixed(3));
let today = new Date(response.dt * 1);
const options = {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
};
let date = today.toLocaleDateString("en-EN", options);
setDate(date);
//ws.close();
};
ws.onclose = () => {
console.log("Connection Closed!");
//initWebsocket();
};
ws.onerror = () => {
console.log("WS Error");
};
};
useEffect(() => {
initWebsocket();
// cleanup method which will be called before next execution. in your case unmount.
return () => {
ws.close();
};
}, []);
// useEffect(() => {
// setTimeout(initWebsocket(), 10000);
// }, []);
return (
<div>
Price : {price}
Last Update: {date}
</div>
);
}
export default Data;
关于这个的两个问题:
- 使用此代码,在某些时候我收到资源不足错误,但数据仍在检索...我不知道为什么。 2) 如果我使用注释的 useEffect 除了 setTimeout 之外它仍然从网络套接字获取数据...我怎样才能每 10 秒获取一次数据?
您可以使用 setInterval 运行 定义周期内的代码块。
setInterval(()=>{your function}, 10000)
这只是您上一个问题的答案。如果您想定期 运行 一个代码,setInterval 是您的不二之选。
我在代码沙箱中稍微编辑了你的代码:
import "./styles.css";
import { useState, useEffect } from "react";
export default function App() {
const [price, setPrice] = useState("");
const [date, setDate] = useState("");
const subscription = { topic: "subscribe", to: "EURUSD:CUR" };
useEffect(() => {
const ws = new WebSocket(
"wss://stream.tradingeconomics.com/?client=guest:guest"
);
ws.onopen = () => {
console.log("Connection Established!");
ws.send(JSON.stringify(subscription));
};
ws.onmessage = (event) => {
const response = JSON.parse(event.data);
console.log(response);
if (response.topic === "EURUSD") {
setPrice(response.price.toFixed(3));
let today = new Date(response.dt * 1);
const options = {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric"
};
let date = today.toLocaleDateString("en-EN", options);
setDate(date);
}
//ws.close();
};
ws.onclose = () => {
console.log("Connection Closed!");
//initWebsocket();
};
ws.onerror = () => {
console.log("WS Error");
};
return () => {
ws.close();
};
}, []);
// useEffect(() => {
// setTimeout(initWebsocket(), 10000);
// }, []);
return (
<div>
<p>Price : {price}</p>
<p>Last Update: {date}</p>
</div>
);
}
我所做的,基本上是将整个套接字连接放在 useEffect 中,并为响应设置一个 if 条件。
https://codesandbox.io/embed/dark-fog-msg3v?fontsize=14&hidenavigation=1&theme=dark