简体   繁体   English

从 WebSocket React 获取数据

[英]Fetching Data from WebSocket React

I'm getting data from a Websocketin a Component:我正在从组件中的 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;

Two questions about this:关于这个的两个问题:

  1. with this code, at some point I get the Insuficient Resources Error, but the data still retrieves... I dont know why.使用此代码,在某些时候我得到资源不足错误,但数据仍然检索......我不知道为什么。 2)if I use the commented useEffect it still getting data from the web socket besides the setTimeout... How can I get data only every 10 seconds? 2)如果我使用注释的 useEffect 除了 setTimeout 之外,它仍然从 web 套接字获取数据......我怎样才能每 10 秒获取一次数据?

you can use setInterval to run a code block within defined period.您可以使用 setInterval 在定义的时间段内运行代码块。

setInterval(()=>{your function}, 10000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM