You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MERN栈中Delete方法调用无响应问题求助

MERN栈社交应用删除按钮无响应问题解决

问题描述

首次实践MERN栈开发,参考教程修改为社交类应用。后端接口经Postman测试功能正常,但React项目中点击删除按钮时无请求响应,其余功能均正常。目标是实现删除MongoDB中的帖子并同步更新前端UI,怀疑问题出在按钮的props使用上。

相关代码

Feed.js

import React, {Component} from "react"
import Card from 'react-bootstrap/Card';
import Button from 'react-bootstrap/Button';
import axios from 'axios';
import {Link} from "react-router-dom"

const renderCard = props => {
   return (
    <>
      <Card style={{ width: '30rem', marginLeft:'auto', marginRight:'auto'}}>
      <Card.Body>
        <Card.Title>{props.username} says: </Card.Title>
        <Card.Text> {props.text}</Card.Text>
       <Link to = {"/edit/"+ props._id}>
        <Button style={{marginRight: '10px'}} variant="secondary">Edit {props.username}'s Profile</Button>
       </Link>
        <Button variant="danger" onClick = {props.deletePost(props.id)}>Delete Post</Button>{' '}
      </Card.Body>
    </Card>
    <br/>
    </>
     )
}
export default class Feed extends Component {

  constructor(props) {
    super(props);

    this.deletePost = this.deletePost.bind(this)

    this.state = {
      postedBy: '',
      username: '',
      text: '',
      id: '',
      posts: []
    };
  }

  componentDidMount() {
    axios.get('http://localhost:9998/posts/')
      .then(response => {
        this.setState({ posts: response.data })
      })
      .catch((error) => {
        console.log(error);
      })
  }


  deletePost(id) {
    axios.delete('http://localhost:9998/posts/'+id)
      .then(response => { console.log(response.data)});

    this.setState({
      posts: this.state.posts.filter(element => element._id !== id)
    })
  }

   render() {
    return (
    <div>
      <h1 style = {{marginLeft:'auto', marginRight:'auto'}}>Home</h1>
      <hr/>
    <div>{this.state.posts.map(renderCard)} </div> 
    </div>
    )
   }
}

Posts.js (路由文件)

const router = require("express").Router();
let Post = require("../models/posts.model");

// 获取所有帖子
router.route("/").get((req, res) => {
    Post.find()
      .then((posts) => res.json(posts))
      .catch((err) => res.status(400).json("Error " + err));
  });

// 添加新帖子
router.route("/add").post((req, res) => {
    const text = req.body.text; 
    const photo = req.body.photo;
    const likes = req.body.likes;
    const comments = req.body.comments;
    const created = req.body.created;
    const username = req.body.username;

    const newPost = new Post ({
        text,
        photo,
        likes,
        comments,
        created,
        username
    });

    newPost.save()
      .then(() => res.json("Post added!"))
      .catch((err) => res.status(400).json("Error: " + err))

});

// 删除帖子
router.route("/:id").delete((req, res) => {
    Post.findByIdAndDelete(req.params.id)
      .then(() => res.json("Post deleted!"))
      .catch((err) => res.status(400).json("Error: " + err))
});

module.exports = router;

问题定位与修复方案

你怀疑的这行代码确实存在三个关键问题:

<Button variant="danger" onClick = {props.deletePost(props.id)}>Delete Post</Button>{' '}

核心问题拆解

  1. onClick直接执行函数:当前写法会在组件挂载时立即调用deletePost,而非点击按钮时触发,需要传递函数引用而非执行结果。
  2. ID字段错误:MongoDB文档主键是_id而非id,props.id会传递undefined,导致后端无法找到对应帖子。
  3. 未传递删除方法:Feed组件的map调用未将deletePost方法传给renderCard,导致子组件props中无此方法。

具体修复步骤

  1. 修改Feed组件中renderCard的调用,传递删除方法和正确的ID:
<div>{this.state.posts.map(post => renderCard({...post, deletePost: this.deletePost}))} </div>
  1. 修正删除按钮的onClick事件,用箭头函数包裹确保点击触发,并使用正确的_id:
<Button variant="danger" onClick={() => props.deletePost(props._id)}>Delete Post</Button>{' '}
  1. 优化deletePost方法,确保后端删除成功后再更新UI,避免网络延迟导致数据不一致:
deletePost(id) {
  axios.delete(`http://localhost:9998/posts/${id}`)
    .then(response => {
      console.log(response.data);
      // 基于prevState更新,避免状态快照问题
      this.setState(prevState => ({
        posts: prevState.posts.filter(element => element._id !== id)
      }));
    })
    .catch(error => {
      console.error('删除失败:', error);
    });
}

完成以上修改后,点击删除按钮即可触发后端请求,成功删除MongoDB中的帖子并同步更新前端UI。

内容的提问来源于stack exchange,提问作者vshjnsfns

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:20:34