Fel*_*res 3 websocket reactjs react-hooks
在此先感谢您的任何建议。我在这里在 ReactJS 中实现 websocket,我的目标是用即将到来的“onmessage”事件填充我的历史状态。对我来说奇怪的是,setHistory在收到来自“websocket.onmessage”事件的消息后清空了我的数组。它甚至消除了我的初始状态。简化版本如下:
function NotificationWebSocket ({object_id}) {
const [history, setHistory] = useState([{text: "The first notification"}]) //
function connectToWebSocket() {
const wsStart = (window.location.protocol === "https:" ? "wss://" : "ws://")
const url = 'localhost:8000/live/'
let socket = new ReconnectingWebSocket(wsStart + url + object_id)
socket.onmessage = e => {
console.log(e.data) // logs the received data correctly
setHistory([...history, {text: e.data}]) // ?? this is setting my history state array to null... ??
setHistory(history.append({text: e.data})) //also cleans my history array here.
}
}
useEffect(() => {
connectToWebSocket()
},[]) // so that we only connect to the websocket once
return (
<div>
We are on a live connection to the server.
{history.map(item=> <div>{item.text}</div>)}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
这里需要注意的是:我正在使用 ReconnectingWebSocket 库,尽管我尝试不使用它并且发生了同样的事情。我的 connectToWebSocket 是从 useEffect 内部触发的,否则我会在服务器中收到几个 websockets 请求。
再次感谢,费利佩。
小智 6
您可以简单地setHistory([...history, {text: e.data}])使用以下代码进行更改setHistory(history=> [...history, {text: e.data}])
| 归档时间: |
|
| 查看次数: |
1567 次 |
| 最近记录: |