如何解决MERN,猫鼬:我将一个数组随机化并保存到Mongo,但是我必须刷新页面
比赛应用程序。
用户注册时,他们存储在Tournament.participants
数组中。
比赛开始时,Tournament.participants
中的所有用户将被随机分配并推送到Tournament.bracket.players
处理此问题的路由:
router.post('/:id/shuffle-players',(req,res) => {
const shuffleParticipants = array => {
let currentIndex = array.length,temporaryValue,randomIndex;
while(0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
};
Tournament.findByIdAndUpdate(req.params.id)
.then(tournament => {
if(!tournament) res.status(404).json({ msg: "Cannot find this tournament" });
else {
const { participants } = req.body;
const { players } = tournament.bracket;
if(players.length !== participants.length) {
const shuffledPlayers = shuffleParticipants(participants);
shuffledPlayers.forEach(player => {
players.push(player);
});
};
return tournament.save();
};
})
.then(savedTournament => res.json(savedTournament))
.catch(err => res.json(err));
});
播放器按随机顺序随机播放,并且正确显示在前端。
问题在于,当第一次渲染组件时,Tournament.bracket.players
会以原始顺序显示。
这很奇怪,因为这表明组件在Post请求之前呈现,但事实并非如此,因为Tournament.bracket.players
在请求之前为空,因此组件应该损坏。
我必须刷新页面才能将它们随机分配。
这是带有Redux的MERN应用程序,我可以发布reducer / action逻辑,但是我不知道这是否是一个问题。
组件:
export const HostUI = ({ tournament }) => {
const { players } = tournament.bracket;
return (
<div style={{color:"lightgrey"}}>
<h1>Host UI</h1>
{
players && players.map(player => (
<div>
{player.username}
</div>
))
}
</div>
);
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。