【发布时间】:2020-11-28 14:51:16
【问题描述】:
应用程序
我正在开发这个应用程序,它从服务器加载数据并将其显示在图表上,并在仪表中显示总数。当新数据存储在数据库上时,服务器也会发出一个事件。 在 App.tsx 中,我执行 API 调用并开始监听此事件。
问题
API 调用工作正常,所有数据都已加载并显示,问题出在 socketio 事件回调中。 events 数组为空,currentTotal 为零,即初始值。我认为问题与 useState 钩子的错误使用有关,但我真的不知道该怎么做。
我尝试将 socket.on() 放在另一个 useEffect 中,甚至放在 useState 钩子的同一范围内,但它只是创建了很多渲染,页面最终需要几秒钟才能加载.
这是我的 App.tsx 文件
...
const [events, setEvents] = useState<Event[]>([])
const [currentTotal, setCurrentTotal] = useState<number>(0)
useEffect(() => {
api
.get('/events')
.then((response) => {
const total = totals(response.data)
setCurrentTotal(total)
setEvents(response.data)
})
.catch()
socket.on('event-created', (newEvent: Event) => {
if (newEvent.rule_name === 'entering') {
newEvent.total = currentTotal + 1
} else {
newEvent.total = currentTotal - 1
}
setCurrentTotal(newEvent.total)
setEvents([...events, newEvent])
})
})
...
这是我在 src/services/socketio.ts
中的套接字服务import { io } from 'socket.io-client'
const socket = io('http://127.0.0.1:4001/')
export default socket
【问题讨论】:
标签: reactjs typescript socket.io