javascript - 根据服务器状态动态更新 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>
)}
导出默认播放器列表;
这将显示已登录玩家的姓名以及已登录大厅的任何其他玩家的姓名。
但我的问题是已经登录的玩家如何了解新加入的玩家。
可能的方法
以每 2 秒的时间间隔发送一个请求。
setInterval(httpRequest,2000);
这是正确的方法吗?有没有其他方法?
组件如何根据后端的变化动态更新其状态?并通过重新渲染组件以反映更改来响应更改。
解决方案
那很接近。使用“componentDidMount”useEffect
钩子模式,即提供一个空的依赖数组([]
)。将 GET 请求重构为在间隔上调用的回调函数,并且不要忘记在此组件卸载时返回效果清理函数以清除间隔。
useEffect(() => {
const timerId = setInterval(() => {
axios.get("http://localhost:8080/game/lobby/" + gamePin)
.then(response => setPlayerList(response.data))
}, 2000);
return () => clearInterval(timerId);
}, []);
推荐阅读
- ios - 启动图像和打开动画是否会导致我的应用冻结?
- javascript - 在 React 中更改所需的输入消息
- java - 未找到表“SPRING_SESSION”
- html - 如何在li中间垂直对齐文本
- javascript - 使用 JavaScript 从对象列表中删除元素
- javascript - JavaScript/HTML:如何在点击“提交”按钮之前显示所有输入值?
- javascript - C# 以编程方式单击 geckofx Web 浏览器中的 div?
- python - scikit-learn:从管道中检索模型对象
- r - 在 ggplot2 r 中操纵 geom_bar 和 coord_polar 的描绘
- c# - VSTS REST API for C# - 如何从工作项中获取链接提交?