React应用需要两次点击来显示axios put请求后的更新状态



我正在构建一个React应用程序,我需要在点击按钮时更新MongoDB数据库中的文档。更新似乎工作得很好,但只有在第二次点击按钮后。

我对它进行了设置,这样当我单击一个按钮时,我调用一个函数来发出axios put请求,然后基本上将用户重定向回同一页面以查看结果。在进行重定向之前,我记录了来自put请求的响应。该日志似乎总是比当前状态晚一个状态。

这些按钮根据文档中更新的值改变颜色。这东西管用,但它总是落后我一步!

import { useState } from 'react';
import axios from 'axios';
import {
Button,
Paper,
Table,
TableBody,
TableCell,
TableHead,
TableRow
} from "@mui/material";
import { useNavigate, useOutletContext } from "react-router-dom";
const Game1 = () => {
const navigate = useNavigate();
const players = useOutletContext();
const updatePlayer = (status, id) => {
axios.put(`http://localhost:5000/api/players/${id}`, { game1: status })
.then(res => {
console.log(res.data);
navigate('/status/game/1')
})
.catch(err => console.log(err))
}
return (
<Paper
style={{ padding: '1em' }}
elevation={ 2 }
>
<Table>
<TableHead>
<TableRow>
<TableCell>PLAYER NAME</TableCell>
<TableCell>PLAYING</TableCell>
<TableCell>NOT PLAYING</TableCell>
<TableCell>UNDECIDED</TableCell>
</TableRow>
</TableHead>
<TableBody>
{
players &&
players.map(player => {
return (
<TableRow key={ player._id }>
<TableCell>
{ player.fullName.toUpperCase() }
</TableCell>
<TableCell>
<Button
variant="contained"
size="small"
color={
player.game1 === 'Playing' ?
'success': 'primary'
}
onClick={ () => updatePlayer('Playing', player._id) }
>
Playing
</Button>
</TableCell>
<TableCell>
<Button
variant="contained"
size="small"
color={
player.game1 === 'Not Playing' ?
'error': 'primary'
}
onClick={ () => updatePlayer('Not Playing', player._id) }
>
Not Playing
</Button>
</TableCell>
<TableCell>
<Button
variant="contained"
size="small"
color={
player.game1 === 'Undecided' ?
'warning': 'primary'
}
onClick={ () => updatePlayer('Undecided', player._id) }
>
Undecided
</Button>
</TableCell>
</TableRow>
)
})
}
</TableBody>
</Table>
</Paper>
)
}
export default Game1;

我快疯了!谁能告诉我我哪里做错了?如有任何帮助,不胜感激。

一切似乎都是正确的,你有没有尝试在updatePlayer函数中使用async/await或者添加type="button"到你的按钮道具

我不确定他们是否能解决你的问题,但如果你能解决,请告诉我

最新更新