首页 > 解决方案 > 根据服务器状态动态更新 React 组件状态

问题描述

我有一个组件,该组件一加载就显示没有玩家登录。

function PlayerList({gamePin}){
const [playerList, setPlayerList] = useState("");
useEffect( ()=>{
    axios.get("http://localhost:8080/game/lobby/"+gamePin)
         .then( response =>{
             setPlayerList(response.data)
         })
})
return(
    <div className='container'>
        <div className='lobbycontainer'>
            <h1>Lobby</h1>
            <Grid container spacing={3}>
                {playerList.map(player=>{
                    <Player {PlayerName,PlayerId} />
                })}
            </Grid>
        </div>
    </div>
    )}

导出默认播放器列表;

这将显示已登录玩家的姓名以及已登录大厅的任何其他玩家的姓名。

但我的问题是已经登录的玩家如何了解新加入的玩家。

可能的方法

  1. 以每 2 秒的时间间隔发送一个请求。

    setInterval(httpRequest,2000);

这是正确的方法吗?有没有其他方法?

组件如何根据后端的变化动态更新其状态?并通过重新渲染组件以反映更改来响应更改。

标签: javascriptreactjsecmascript-6react-hooks

解决方案


那很接近。使用“componentDidMount”useEffect钩子模式,即提供一个空的依赖数组([])。将 GET 请求重构为在间隔上调用的回调函数,并且不要忘记在此组件卸载时返回效果清理函数以清除间隔。

useEffect(() => {
  const timerId = setInterval(() => {
    axios.get("http://localhost:8080/game/lobby/" + gamePin)
      .then(response => setPlayerList(response.data))
  }, 2000);

  return () => clearInterval(timerId);
}, []);

推荐阅读