【发布时间】:2021-04-30 06:07:33
【问题描述】:
我正在学习这些技术(React JS、Node、WebSockets),并正在从事一个使用 websockets 在图形上实时显示信息的项目。
我的组件中有一个状态,它存储具有不同属性的对象数组。
当我向我的服务器发出 POST 请求时,记录会保存在数据库中(在 PostgreSQL 中制作),我会通知客户端进行更新
我的问题是当我刷新页面时它停止工作,我需要重新启动服务器才能再次看到图表中的更改。
服务器
io.on('connection', client => {
app.post("/registros/nuevo", async (req, res) => {
try {
let insertar = await pool.query(`INSERT INTO registro
(fecha, hora, temperatura, presion, humedad, viento, viento_max, radiacion, precipitacion)
VALUES
('${req.body.fecha}', '${req.body.hora}', ${req.body.temperatura}, ${req.body.presion},
${req.body.humedad}, ${req.body.viento}, ${req.body.viento_max}, ${req.body.radiacion},
${req.body.precipitacion});`).then(() => { client.emit('new: data', 'updated') });
res.json({ message: "Recibido" });
} catch (err) {
console.error(err.message);
}
});
});
客户
const [data, setData] = useState([])
const getData = async () => {
try {
const response = await fetch("http://localhost:5000/registros");
const jsonData = await response.json();
setData(jsonData);
setCurrent(jsonData[jsonData.length - 1])
} catch (err) {
console.error(err.message)
}
};
useEffect(() => {
getData()
}, [])
useEffect(() =>{
socket.on('new: data', (c) =>{
console.log(c)
getData()
})
}, []);
我知道我的代码不是最好的,感谢您的帮助
【问题讨论】:
标签: node.js reactjs socket.io recharts