【问题标题】:How to properly use DELETE by ID in Node.js/ReactJS如何在 Node.js/ReactJS 中按 ID 正确使用 DELETE
【发布时间】:2020-03-16 19:25:28
【问题描述】:

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

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

这里我先得到一个get

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);
   }
   });
   });

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

我该如何解决这个问题?

【问题讨论】:

    标签: javascript node.js reactjs express fetch


    【解决方案1】:

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

    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 }));
    

    ,在渲染方法中你可以将id作为变量传递给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);
          }
       });
    });
    

    【讨论】:

    • 控制台在connection.query中记录err,DB查询可能有问题
    • code: 'ER_PARSE_ERROR', errno: 1064, sqlMessage: "您的 SQL 语法有错误;请查看与您的 MariaDB 服务器版本相对应的手册,了解在 '' 附近使用的正确语法第 1 行",sqlState:'42000',索引:0,sql:'DELETE from alluserpls WHERE id = '} DELETE /api/alluserpls 500 15.629 ms - 40
    • 您是否为按钮添加了id 属性?像这样&lt;button id={datass.id} type="submit"&gt;Delete&lt;/button&gt;
    • 我已经编辑了我的答案,你能检查一下是否有效!
    • 我也有类似的问题,你觉得我可以在这里问吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2018-01-12
    相关资源
    最近更新 更多