【问题标题】:how to delete a post from database in React Native?如何在 React Native 中从数据库中删除帖子?
【发布时间】:2021-02-26 18:20:31
【问题描述】:

我正在尝试按其 ID 从数据库中删除帖子。我能够在 React Native 中实现 get 和 post 方法,但是当我尝试删除它时不起作用。

这是我在后端的删除方法:-

 router.delete("/:id", (req, res) => {
 let { id } = req.params;
 Post.findByPk(id).then((post) => {
if (post) {
  return post.destroy().then(() => {
    res.status(204).send();
  });
} else {
  res.status(404).send();
}
  });
});

在 React Native 中,这里是我当前使用的代码:

 const deletePost = () => client.delete("/posts/:id");

这是我的按钮,按下时会调用 handleDelete 函数:

<Button title="Delete" onPress={handleDelete}/>

到目前为止,这是我的句柄删除:

const handleDelete = () => {
  Alert.alert("Delete", "Are you sure you want to delete this post?", [
    { text: "Yes", onPress=},
    { text: "No" },
  ]);
 };

有人可以帮我完成这个吗?如何在我的 onPress 中调用 deletePost 方法?

这是我在后端的帖子模型:

const Post = db.define(
 "Post",
 {
id: {
  type: Sequelize.INTEGER,
  primaryKey: true,
  autoIncrement: true,
},
title: {
  type: Sequelize.STRING,
  })

【问题讨论】:

    标签: node.js react-native rest


    【解决方案1】:

    您没有从客户端发送 id。您在该路由中传递了一个字符串 ":id"。试试下面的代码。

    const deletePost = (id) => client.delete(`/posts/${id}`);
    
    const handleDelete = (id) => {
      Alert.alert("Delete", "Are you sure you want to delete this post?", [
        { text: "Yes", onPress: () => deletePost(id) },
        { text: "No" },
      ]);
     };

    【讨论】:

    • 嗨 nazeer,我尝试了一些非常相似的方法,它奏效了。 const deletePost = (PostId) => client.delete(/posts/${PostId}); const handleDelete = () => { Alert.alert("Delete", "你确定要删除这篇文章吗?", [ { text: "Yes", onPress: () => deletePost(post.id) } , { text: "否" }, ]); };
    • 你能解释一下我的代码是如何工作的吗? PostID 是数据库中的列
    • 很高兴知道这一点。将此设置为答案,以便其他人可以知道正确的方法。谢谢
    • @kd12345 您只是在 POST MODEL 中执行 Post.findByPk(id) 以通过 id 查找然后销毁它。这与您的 PostID 列无关。顺便说一句,我是前端专家而不是后端,但我可以理解你的 api 代码。
    • 所以这里 const deletePost = (PostId) => client.delete(/posts/${PostId}) 而不是 PostId 我称之为什么?
    【解决方案2】:

    试试这个方法

    const handleDelete = () => {
      Alert.alert("Delete", "Are you sure you want to delete this post?", [
        { text: "Yes", onPress: () => deletePost() },
        { text: "No" },
      ]);
     };
    

    【讨论】:

    • 在前端,当我这样做时,由于 onPress 后的 =,我收到了一个意外的令牌错误,当我将其更改为 : 时,在我的后端我收到此错误 SequelizeDatabaseError: invalid input syntax for type integer: ":id"
    • 试试这种方式onPress: () =&gt; {...} 因为我也更新了我的答案
    • 像这样 { text: "Yes", onPress: () => {deletePost()} } ?
    • 在后端我仍然收到此错误 SequelizeDatabaseError: invalid input syntax for type integer: ":id"
    • 我认为id 的类型在进入后端时不正确或无效。您期待integer,但事实并非如此。你可以查看帖子的id 吗?到底是什么?或分享更多信息代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多