reactjs - axios删除请求完成后如何从React组件中的数组中删除项目?
问题描述
我已经构建了一个 React 组件,它在数组中显示从 MongoDB 返回的项目列表。可以修改或删除各个项目。要删除项目,用户单击一个按钮,该按钮在子组件内打开一个模式窗口。用户删除项目后,应从“匹配”数组中删除该项目,并且应自动重新渲染父组件,并显示更新的数组。
我构建了一个名为 handleUpdate() 的函数,它应该在 axios 删除请求完成后从数组中过滤掉已删除的项目。这是我遇到问题的地方,因为虽然实际的 axios 删除请求按预期工作,但只有当手动刷新组件时,数组才会显示更新的项目列表。
有人可以解释一下如何让组件在删除请求后自动刷新/更新,并从数组中删除已删除的数据吗?预先感谢您的任何帮助。
主要组件代码:
export default function UpcomingFixtures() {
const [matches, setMatches] = useState([]);
const [pageNumber, setPageNumber] = useState(1)
const [loading, setLoading] = useState(true)
const url = "http://localhost:5000/match";
useEffect(() => {
upcomingMatches(page number);
}, [pageNumber])
const upcomingMatches = async (pageNumber) => {
try {
await axios
.get(`${url}/paginate/${team}?page=${pageNumber}&limit=5`)
.then( res => {
setMatches(p => [...p, ...res.data.results]);
setLoading(false)
});
} catch(err) {
console.error(err);
}
}
const handleUpdate = () => {
const newMatches = matches.filter(match => match.id !== id)
setMatches(newMatches);
}
return (
(matches.map(match => {
const { myTeam, opposition, homeAway, createdAt, _id } = match
return (
<Card variant="outlined" key={match._id}>
<CardContent>...</CardContent>
<Button type="submit">
<DeleteMatchDialog
myTeam={myTeam}
opposition={opposition}
id={_id}
handleUpdate={handleUpdate}/>
</Button>
</Card>
)});
删除模态代码:
export default function DeleteMatchDialog(props) {
//props
const { id, handleUpdate, opposition } = props;
const deleteMatch = async (e) => {
e.preventDefault();
try {
await axios.delete(`${url}/delete/${id}`)
.then(res => {
handleUpdate(id);
})
} catch (err) {
console.log(err)
}
}
return (
<Button onClick={handleDelete} Delete </Button>
<Dialog>
<form onSubmit={deleteMatch}>
<Button type="submit">
Delete
</Button>
</form>
</Dialog>
);
}
编辑 - 更新问题 15/05/21
解决方案
推荐阅读
- google-sheets - 谷歌电子表格中用于在搜索结果之间切换的键盘快捷键
- vue.js - 使用 Quasar (Vue) 将数据写入 Google 表格
- jsonschema - 在 JSON 模式中,定义和引用可重用的枚举类型?
- json - MongoDB插入嵌套数据
- python - python中的基本函数
- reactjs - 为什么我不能从 api/context 中获取项目?(反应问题)
- c# - 在 c# 中使用 Newtonsoft 对 Json 中的嵌套对象进行有效的手动反序列化
- assembly - 即使我确实为变量设置了初始值,数据段也没有被初始化
- go - 发送蓝牙广告包并获得一些答案
- ssh - 如何通过 ssh 调用 AAC 音频流功能