简体   繁体   English

更新 React 组件 state 基于服务器动态更新 state

[英]Updating React Component state Dynamically based on server state

I have a component that shows no of players logged in as soon as the component loads.我有一个组件,在组件加载后立即显示没有玩家登录。

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>
    )}

export default PlayerList;导出默认播放器列表;

This will display the name of the player who is logged in and any other players already logged into the lobby.这将显示已登录玩家的姓名以及已登录大厅的任何其他玩家。

But my question is how do the players who are already logged in will get to know about the new players who joined.但是我的问题是已经登录的玩家如何知道新加入的玩家。

Possible Approach可能的方法

  1. Send a request with a time interval of every 2 seconds.每 2 秒发送一次请求。

    setInterval(httpRequest,2000); setInterval(httpRequest,2000);

Is this the right way to do this?这是正确的方法吗? are there any alternate approaches?有没有其他方法?

How does a component dynamically update its state based on the changes in the backend?一个组件如何根据后端的变化动态更新它的state? and respond to the changes by rerendering the component to reflect the changes.并通过重新渲染组件来响应更改以反映更改。

That is pretty close.这非常接近。 Use a "componentDidMount" useEffect hook patter, ie provide an empty dependency array ( [] ).使用“componentDidMount” useEffect挂钩模式,即提供一个空的依赖数组( [] )。 Refactor the GET request into a callback function invoked on an interval and don't forget to return an effect cleanup function to clear the interval when this component unmounts.将 GET 请求重构为按间隔调用的回调 function,并且不要忘记返回效果清理 function 以在该组件卸载时清除间隔。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM