首页 > 解决方案 > 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

标签: reactjsreact-hooks

解决方案


推荐阅读