如何解决MERN和Redux:将发送给后端的未持久化对象数组随机化
我正在使用一个组件来更改名为Tournament的模型的两个属性。 Tournament.status和Tournament。参与者。
状态从“打开”更改为“关闭”。
参与者,我将他们随机分组,然后保存新值。
由于某些原因,只有对status
的更改仍然存在,而对participants
的更改却没有。
我的后端路线:
router.post('/update/:id',(req,res) => {
Tournament.findById(req.params.id)
.then(tournament => {
if(!tournament) res.status(404).json({ msg: "Cannot find this tournament" });
else {
if(req.body.status && req.body.participants) {
tournament.status = req.body.status;
tournament.participants = req.body.participants;
} else {
return res.status(404).json({ msg: "Both status and participants required" });
}
};
return tournament.save();
})
.then(savedTournament => res.json(savedTournament))
.catch(err => res.json(err));
});
我用Postman进行了测试,传入了一个新的状态字符串和一组参与者(我手动更改了参与者的顺序),并且它可以正常工作。它保留了两者的新值。
我用来随机化数组的函数是:
export 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;
};
最初,我在Express Route中拥有该功能,但是现在我将其与调用它的功能一起放置为Redux动作功能:
export const updateTournamentStatus = (_id,status,participants) => dispatch => {
const config = {
headers: {
"Content-Type": "application/json"
}
};
const body = JSON.stringify({ status,participants});
axios
.post(`/tournaments/update/${_id}`,body,config)
.then(() => dispatch({
type: TOURNAMENT_STATUS_UPDATE,payload: {
status: status,participants: shuffleParticipants(participants); // <<~~ shuffle function here
}
}))
.catch(err => {
dispatch(returnErrors(err.response.data,err.response.status));
dispatch({
type: TOURNAMENT_STATUS_FAILED
})
});
};
以防万一与我的减速器有关,这是我的设置:
const initialState = {
tournaments: [],showTournament: "",loading: false,}
...
case TOURNAMENT_STATUS_UPDATE:
return {
...state,...state.showTournament.status = action.payload.status,...state.showTournament.participants = action.payload.participants
};
摘要:尝试配置一项功能,通过更改比赛的状态并随机分配参与者列表来启动比赛。
上面的代码更改状态并随机分配参与者,并使用新的状态和参与者的新顺序重新呈现组件,但后端仅更改新的状态。
当我刷新时,参与者会恢复到原来的顺序。
不确定我在做什么错。谢谢大家。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。