如何在更改数据库后立即呈现组件



我已经创建了一个页面,用户将看到一些产品。每个产品都有送货按钮。如果用户点击交付按钮,产品数量将减少1。然后它会立即渲染组件并显示新的数量

我使用状态来设置产品。假设有一个量和一个结构化量

const [product, setProduct] = useState({});
const { quantity} = product;

我设置了一个函数使这个量减少1

function removeOne() {
let newQuantity = quantity - 1;
const newProduct = { ...product, quantity: newQuantity }
//copy all previous data if exist in product and setup new quantity 
setProduct(newProduct);
fetch(`your server link/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newProduct)
})
}
<button onClick={() => removeOne(id)}}>Button</button>

最新更新