我有一个socket
用于调度和侦听来自服务器的事件的类。
该类具有在和state
之间进行同步的方法。server
client
以下是我如何监听来自服务器的更改或事件。
import React, { useEffect, useState } from 'react'
import { useStore } from "./store"; // this is a zustand store object
import Game from "./game";
export const Lobby = ({ user }) => {
const players = useStore(state => state.players);
const dispatch = useStore(state => state.dispatch)
const addPlayer = (player) => {
dispatch({ type: "NEW_PLAYER", player })
}
useEffect(() => {
// inside Game -> this.eventListeners[key].push(cb)
Game.register('new-palyer', addPlayer);
}, [])
return (
<div>
{
players.map(player => <span>{player.name}</span>)
}
</div>
)
}
还有另一种方法是订阅类store
内部并使用任何更改来更新。在对这些侦听器和调度程序的当前结构进行任何更改之前,我没有实现任何东西,我需要通过列出每个范例的and来做出更好的决定。如果通过中间件范式的真实示例来回答,我将不胜感激。Game
store
pros
cons