首页 > 解决方案 > 如何在 Node.js/ReactJS 中按 ID 正确使用 DELETE

问题描述

我想解释一下我今天遇到的问题。

我认为这比平时更难,所以让我解释一下

在这里,我首先得到一个

getRandom = async () => {
const res = await axios.get(
entrypoint + "/alluserpls"
)
this.setState({ data: res.data })
}
componentDidMount() {
this.getRandom()
}

这是我的删除方法

handleSubmit = (e) => {
e.preventDefault();
const config = {
  method: "DELETE",
  headers: {
    "Content-Type": "application/json",
  },
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
  .then(res => res.json())
  .then(res => {
    if (res.error) {
      alert(res.error);
    } else {
      alert(`ajouté avec l'ID ${res}!`);
    }
  }).catch(e => {
    console.error(e);
  }).finally(() => this.setState({ redirect: true }));

}

然后我映射它

 render() {
 let datas = this.state.data.map((datass, index) => {
 return (
     <Col sm="12" key={index}>
     <form onSubmit={this.handleSubmit}>
         <button type="submit">Delete</button>
     </form>
        <div>{datass.name}</div>
     </Col>

然后我在我的地图上返回结果

return (
  <div>  
    {datas}
   </div>

所以可以正常工作,但是当我只想删除 1 张卡时,问题如下,它会删除我所有的 BDD

这是我在 BDD 上的路线

   app.delete('/api/alluserpls', (req, res, ) => {
   const formData = req.body;
   connection.query('DELETE FROM alluserpls SET ?', formData, err => {
   if (err) {
   res.status(500).send("Erreur lors de la modification des users");
   } else {
   res.sendStatus(200);
   }
   });
   });

我希望当我点击删除它只删除卡而不是我的所有数据库。

我该如何解决这个问题?

标签: javascriptnode.jsreactjsexpressfetch

解决方案


这是一种方法,将id用户分配给按钮id属性字段,然后与用户一起调用删除 APIid

handleSubmit = (e, id) => {
e.preventDefault();
const userIdData = { id };
const config = {
  method: "DELETE",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(userIdData), 
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
  .then(res => res.json())
  .then(res => {
    if (res.error) {
      alert(res.error);
    } else {
      alert(`ajouté avec l'ID ${res}!`);
    }
  }).catch(e => {
    console.error(e);
  }).finally(() => this.setState({ redirect: true }));

, 在 render 方法中你可以将idas 变量传递给handleSubmit函数

render() {
 let datas = this.state.data.map((datass, index) => {
 return (
     <Col sm="12" key={index}>
     <form onSubmit={(e) => this.handleSubmit(e, datass.id)}>
         <button type="submit">Delete</button>
     </form>
        <div>{datass.name}</div>
     </Col>

在后端,您可以获得 id 并仅删除特定用户

app.delete('/api/alluserpls', (req, res, ) => {
   const formData = req.body;
   const userId = req.body.id;
   const deleteQuery = `DELETE from alluserpls WHERE id = ${userId}`;
   connection.query(deleteQuery, err => {
     if (err) {
       res.status(500).send("Erreur lors de la modification des users");
      } else {
       res.sendStatus(200);
      }
   });
});

推荐阅读