reactjs - ReactJS 中的 WebSocket 使用空数组设置状态
问题描述
在此先感谢您的任何建议。我在这里在 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>
)
}
这里要注意的事项:我正在使用 ReconnectingWebSocket 库,尽管我尝试不使用它并且发生了同样的事情。我的 connectToWebSocket 是从 useEffect 内部触发的,否则我会在服务器中收到几个 websockets 请求。
再次感谢,费利佩。
解决方案
您可以简单地setHistory([...history, {text: e.data}])
使用以下代码进行更改setHistory(history=> [...history, {text: e.data}])
推荐阅读
- asp.net-core - asp.net core Identity 15 分钟后自动注销?
- spring - Spring MVC 对移动设备和标准浏览器的支持
- kubernetes - 使用 traefik 入口访问 kibana
- mysql - R 和 DBI dbWriteTable 与 MySQL/MariaDB 的连接仅导入第一行
- html - 将按钮的索引值传递给弹出框组件
- python - 我可以用 xlwings 和 python 在 excel 中创建一个表吗?
- sql - SQL - 每个用户最近完成的五门培训课程
- r - 无法从闪亮的降价报告中的数据库查询中检索数据
- html - 如何正确居中和调整图像大小?
- flutter - 使用预先生成的文件 ID 将文件上传到谷歌驱动器时出现详细 ApiRequestError