【发布时间】:2019-06-16 04:18:54
【问题描述】:
我使用 NodeJS、React 和 SocketIO 开发了一个基本应用程序。
我的 NodeJS 服务器使用玩家表(字符串值)向 React 客户端发送套接字。我想在反应视图中显示这个玩家表,并在它发生变化时动态刷新它。
我尝试了一些解决方案,但效果不佳。你有想法这样做或改进我的代码吗?
谢谢
构造函数:this.players[]
constructor(props){
super(props);
this.state = {
endpoint: "http://127.0.0.1:8080",
}
this.gameId = this.props.match.params.id;
this.players = [];
}
showPlayer : 显示有牌的玩家列表
showPlayers = () => {
const classes = this.props;
let playersCards = [];
console.log(this.players);
this.players.foreach(function(p){
playersCards.push(
<Card className={classes.card}>
<CardHeader
avatar={
<Avatar style={{backgroundColor: "#00FF00"}} aria-label="Recipe">
R
</Avatar>
}
action={
<IconButton>
<MoreVertIcon />
</IconButton>
}
title={p}
subheader=""
/>
</Card>
)
}
return playersCards;
}
Socket.io : 更新玩家列表
socket.on('ack-join-game', function(res){
this.players = res.dataGame.players;
});
渲染:
const classes = this.props;
return(
<div className="GameConfig">
<h1>Salon de jeu</h1>
<div className="well" style={this.wellStyles}>
<h2>Informations</h2>
Id : {this.gameId}
<br></br>
<h2>Players (0/2)</h2>
<div id="cards">
</div>
{this.showPlayers()}
<form onSubmit={this.handleFormSubmit}>
<br></br>
<Button bsStyle="primary" type="submit" bsSize="large" block>
Lancer la partie
</Button>
</form>
</div>
<ToastContainer store={ToastStore}/>
</div>
)
}
【问题讨论】: