【问题标题】:How to implement Axios.delete in react and delete from Mongodb by id如何在反应中实现 Axios.delete 并通过 id 从 Mongodb 中删除
【发布时间】:2020-11-28 03:23:30
【问题描述】:

我是 MERN(编程本身)的新手,我正在尝试通过前端的 ID 从数据库中删除。我希望能够单击项目上的按钮并将其从数据库中删除。

useEffect(() =>{
  Axios.post('api/product/editProducts')
    .then(response => {
      if (response.data.success){
        setProperty(response.data.products)
      }else {
        alert('Failed to get product information')
      }
    })
})

return (
  <div>
    <div style={{ textAlign: 'center', marginTop: '5rem '}}>
      <h1>Edit Properties</h1>
    </div>
    <br />
    <table>
      <thead>
        <tr>
          <th>Product Title</th>
          <th>Price</th>
          <th>Title</th>
          <th>Description</th>
          <th>Rent/Sale</th>
          <th>Edit</th>
          <th>Delete</th>
        </tr>
      </thead>
      <tbody>
        {Property.map(property => (
          <tr key={property.id}>
            <td>{property.title}</td>
            <td>{property.description}</td>
            <td>{property.price}</td>
            <td>{property.properties}</td>                            
            <td>{property.rentorbuy}</td>
            <td>{EditBtn }</td>
            <td><a onClick={handleDeleteProperty}>{DeleteBtn}</a></td>
          </tr>
        ))}

使用上面的代码,我可以从数据库中获取产品。

router.post("/editProducts", auth, (req,res) => {
  Product.find()
    .exec((err,products) => {
      if(err) return res.status(400).json({ success: false, err})
      res.status(200).json({ success: true, products })
    })
});

product display

有人可以帮助我提供如何单击删除 btn(如图所示)并从数据库中删除该特定项目的代码和路线吗?

【问题讨论】:

    标签: reactjs mongodb express axios mern


    【解决方案1】:
    • 你可以这样做

    前端

    const handleDeleteProperty = async (id) => {
        try{
            const res = await Axios.delete('url', id);
            if(res.data.success){
                alert(res.data.msg);
            }
        }
        catch(err){
            console.error(err);
        }
    }
    
    <td><a onClick={e => handleDeleteProperty(property.id)}>{DeleteBtn}</a></td>
    
    

    后台

    router.delete('url', auth, async (req, res) => {
        try{
            await Product.findByIdAndDelete(req.body.id);
            return res.status(200).json({ success: true, msg: 'Product Deleted' });
        }
        catch(err){
            console.error(err);
        }
    });
    
    • 现在已经完成,您可以更优雅地处理错误。

    【讨论】:

    • 非常感谢@AmanBhardwaj。我将在我的新项目中尝试一下
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 2021-03-05
    • 2015-08-25
    • 2021-02-27
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多