gpt4 book ai didi

javascript - 如何从 React 中的 Websocket 获取数据?

转载 作者:行者123 更新时间:2023-12-01 00:35:32 26 4
gpt4 key购买 nike

我正在尝试从 bitstamp API 获取实时数据并将其存储在我的订单状态中。页面陷入循环并耗尽资源,并且当订单状态发生变化时,React 不会重新渲染页面。如果我将其记录到控制台,我可以看到数据

这是我迄今为止所实现的。

  const [loading, setLoading] = useState(true);
const [orders, setOrders] = useState([]);
const [subscription, setSubscription] = useState({
event: 'bts:subscribe',
data: {
channel: 'order_book_btcusd'
}
});
const ws = new WebSocket('wss://ws.bitstamp.net');
const initWebsocket = () => {
ws.onopen = () => {
ws.send(JSON.stringify(subscription));
};
ws.onmessage = (event) => {
const response = JSON.parse(event.data);
switch (response.event) {
case 'data':
setOrders(response.data);
setLoading(false);
break;
case 'bts:request_reconnect':
initWebsocket();
break;
default:
break;
}
};
ws.onclose = () => {
initWebsocket();
};
};

useEffect(() => {
initWebsocket();
}, [orders, subscription]);

console.log(orders);

const showResult = () => {
orders.bids.map((el, index) => (
<tr key={index}>
<td> {el[0]} </td>
<td> {el[1]} </td>
</tr>
));
};

最佳答案

发生这种情况是因为 useEffect 在每个渲染周期后执行其回调,即它在第一次渲染后和每次更新后都运行。因此,对于收到的每条第一条消息,它都会打开一个新的 WebSocket 连接并将数据存储在导致循环的状态中。

You can read more about useEffect here

编辑:-

useEffect(() => {
initWebsocket();
}, [orders, subscription]);

useEffect 的可选第二个参数用于检测是否有任何更改(基本上它会比较之前的状态/属性和给定的状态/属性),并且每当发生更改时都会调用效果值(value)。

因此,在每次 orders 状态更新时,都会调用此效果,从而导致循环。

解决方案:-

但在您的情况下,您只想在组件安装后建立一次 WebSocket 连接,并继续监听传入的数据,而不管任何状态或属性更改。您可以传递一个空的 [],以便在挂载和卸载时仅调用一次。

useEffect(() => {
initWebsocket();
// cleanup method which will be called before next execution. in your case unmount.
return () => {
ws.close
}
}, []);

来自文档:-

This requirement is common enough that it is built into the useEffect Hook API. You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect.

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

If you pass an empty array ([]), the props and state inside the effect will always have their initial values. While passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model, there are usually better solutions to avoid re-running effects too often.

关于javascript - 如何从 React 中的 Websocket 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58155985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com