我是React的新手,我希望将我的React应用程序与websocket连接相结合。
我能够通过websocket连接建立连接,但无法在我的应用程序中显示。
后端代码
#!/usr/bin/env python
import asyncio
import random
import datetime
import websockets
import json
async def handler(websocket, path):
while True:
data = [
{
"name": "Random Int 1",
"number": random.randint(0, 3000),
"category": "Pun"
}
]
await websocket.send(json.dumps(data))
await asyncio.sleep(1)
start_server = websockets.serve(handler, "127.0.0.1", 8888)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
反应代码是
import { useState, useEffect } from "react";
export default function App() {
const [number, setNumber] = useState("");
useEffect(() => {
const ws = new WebSocket("ws://127.0.0.1:8888/");
ws.onopen = () => {
console.log("Connection Established!");};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(data);
setNumber({data.number});};
ws.onclose = () => {
console.log("Connection Closed!");};
ws.onerror = () => {
console.log("WS Error");};
return () => {
ws.close();
};
}, []);
return (<div>
<p>number :{person.number}</p>
</div>
);
}
代码中的几个小错误:
将setNumber()
更新为:
setNumber(data.number);
和person.number
不存在(因为变量只是number
,所以:
<p>number: {number}</p>