首页 > 解决方案 > 尝试创建删除函数(React 前端/Rails 后端)

问题描述

我正在尝试创建一个删除按钮,当点击该按钮时,它会从用户个人资料中删除最喜欢的咖啡店。onClick 达到了我想要的功能,但是当我尝试获取咖啡店的 id 时,它出现空。我试图这样做,${coffee_shop_id}因为它是它通过但不成功时的显示方式,我一直在尝试只是${cafe.id}因为咖啡馆将所有内容都传递回我关于咖啡店的删除功能,但仍然没有运气......

这是我到目前为止所拥有的..

我的功能

        handleRemove = (e) => {
          console.log(e)
          const cafe = {
              coffee_shop_name: this.state.coffee_shop_name,
              coffee_shop_image_url: this.state.coffee_shop_image_url,
              coffee_shop_phone: this.state.coffee_shop_phone,
              coffee_shop_id: this.state.coffee_shop_id,
            }
           this.props.removeFav(cafe)
          }

我的按钮

....
  <button className="submit-removefav" onClick={(e) => {this.handleRemove(e)}}> X </button>

我的删除

removeFav = (cafe) => {
    console.log(cafe)
    fetch(`http://localhost:3000/favorites/${cafe.id}`, {
      method: 'DELETE',
      headers: { 
        "Content-Type" : "application/json",
        Accept: "application/json",
        Authorization: `bearer ${localStorage.token}`
      }
    })
    .then(res => res.json())
  }

下面是我删除的咖啡馆的图片... 在此处输入图像描述

我最喜欢的控制器删除

def destroy
        favorite = Favorite.find(params[:id])
        favorite.destroy
        render json: {message: "Successfully removed favorite"}
    end

任何建议表示赞赏!

标签: ruby-on-railsreactjsfetch

解决方案


在销毁中使用以下内容修复它

favorite = Favorite.find_by(params[:coffee_shop_id])


推荐阅读