简体   繁体   English

如何使用 PATCH 请求更改 true/false 值并在 React 中呈现更改?

[英]How do I use a PATCH request to change a true/false value and render the change in React?

I'm making a shopping app and I want to have a button that sends a PATCH request to my db to update the value cart_status from false to true .我正在制作一个购物应用程序,我希望有一个按钮可以向我的数据库发送 PATCH 请求,以将值cart_statusfalse更新为true I have the button working, but I think my syntax is off on the PATCH function. Also, if anyone is extra helpful, my img tags are not rendering the image and I don't know why (they are external image URLs if that helps).我有按钮工作,但我认为我的语法在PATCH function 上关闭。此外,如果有人特别有用,我的img标签没有呈现图像,我不知道为什么(它们是外部图像 URL,如果有帮助的话) ).

Here is my code:这是我的代码:

import React, { useState } from "react";

function ItemCard({ item }) {

  const [addToCart, setAddToCart] = useState(true)

  const handleAddToCart = () => {
    setAddToCart(addToCart => !addToCart)
    fetch(`/items/${item.id}`, {
      method: 'PATCH',
      headers: {
        "Content-Type": 'application/json',
      },
      body: JSON.stringify(item.cart_status)
    })
      .then(resp => resp.json())
      .then(item(setAddToCart))
  }

  return (
    <div className="card">
      <img src={item.image_url} alt={item.item_name} />
      <h4>{item.item_name}</h4>
      <p>Price: ${item.price}</p>
      <p>* {item.description} *</p>
      {addToCart ? (
        <button className="primary" onClick={handleAddToCart}>Add To Cart</button>
      ) : (
        <button onClick={handleAddToCart}>Remove From Cart</button>
      )}
    </div>
  );
}

export default ItemCard;

The results of clicking the "Add To Cart" button changes the state of the button, but does not update in the db.单击“添加到购物车”按钮的结果更改了按钮的 state,但没有在数据库中更新。 I also get this error message in the terminal:我还在终端中收到此错误消息:

Started PATCH "/items/1" for 127.0.0.1 at 2022-11-08 15:30:14 -0600
Processing by ItemsController#update as */*
  Parameters: {"_json"=>false, "id"=>"1"}
  Item Load (0.2ms)  SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/items_controller.rb:24:in `update'
Unpermitted parameters: :_json, :id
[active_model_serializers] Rendered ItemSerializer with ActiveModelSerializers::Adapter::Attributes (0.38ms)
Completed 202 Accepted in 3ms (Views: 0.7ms | ActiveRecord: 0.2ms | Allocations: 997)

Because true/false are boolean values, you can send a patch request to the rails attribute and use the bang operator "."因为 true/false 是 boolean 值,所以您可以向 rails 属性发送补丁请求并使用 bang 运算符“.” to flip the false on the backend.在后端翻转错误。

import React, { useState } from "react";

function ItemCard({ item }) {
  // console.log(item)
  const [addToCart, setAddToCart] = useState(item.cart_status)

const handleAddToCart = () => {
setAddToCart(addToCart => !addToCart)

fetch(`/items/${item.id}`, {
  method: 'PATCH',
  headers: {
    "Content-Type": 'application/json',
  },
  body: JSON.stringify({ cart_status: !item.cart_status })
})
  .then(resp => resp.json())
  .then(data => console.log(data))

  window.location.reload(false)
}



return (
<div className="card">
  <img src={item.img_url} alt={item.item_name} />
  <h4>{item.item_name}</h4>
  <p>Price: ${item.price}</p>
  <p>* {item.description} *</p>
  {addToCart ? (
    <button onClick={handleAddToCart}>Remove From Cart</button>
  ) : (
    <button className="primary" onClick={handleAddToCart}>Add To Cart</button>
  )}
</div>
);
}

export default ItemCard;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 true 或 false 的值更改为文本值类型 我正在检查整个表中的行 注意该表是数据表类型吗? - How do I change the value of true or false to a text value type it I am checking the row in the entire table Note the table is of type datatables? 如果单击复选框,如何将复选框从true更改为false - React how to change checkbox from true to false if checkbox clicked 我可以将网址中的值从true更改为false - Can I change a value in the url from true to false 反应:如果 1 state 为真,则将其他更改为假 - React: if 1 state is true, change others to false Javascript:使用函数将变量更改为真/假 - Javascript: Use a function to change variables to true/false React - 如何使用 handleInputChange function 来更改 state 值内的 state 值? - React - How do I use a handleInputChange function to change a state value that is within a state value? 复选框更改真假函数值 - Checkbox to change value of a true vs false function 无法将变量的值从true更改为false - Cannot change value of variable from true to false 如何使用angular或javascript基于true / false返回在html中显示值? - How do I use angular or javascript to display value in html based on true/false return? 如何将“条纹”按钮与正确/错误检查一起使用? - How do I use my Stripe button with a true/false check?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM