我试图添加购物车中的特定项目(位于react-db)。Json文件)在按钮上单击,然后在不同的页面上显示它。另外,如果有人有更简单的方法来做这件事,那将非常有帮助
import React, { Component } from "react";
import Product from "./Product.jsx";
import { Kosarica } from "./kosarica.jsx";
import axios from "axios";
export default class Cart extends Component {
constructor(props) {
super(props);
this.state = {
products: []
};
}
render() {
return (
<div>
<div className="row">
{this.state.products.map(prod => {
return (
<Product
key={prod.id}
product={prod}
onIncrement={this.handleIncrement}
onDecrement={this.handleDecrement}
onDelete={this.handleDelete}
>
<button
id="btn"
className="btn btn-primary"
onClick={this.handleClick}
>
Dodaj
</button>
</Product>
);
})}
</div>
</div>
);
}
componentDidMount = async () => {
var response = await fetch("http://localhost:5000/products", {
method: "GET"
});
var prods = await response.json();
this.setState({ products: prods });
};
};
handleClick = product => {
let data = [this.state.products];
fetch("http://localhost:5000/cart", {
method: "POST",
mode: "cors",
body: JSON.stringify(data)
});
console.log("data sent", data);
};
}
注-递增,递减和删除都工作得很好,这就是为什么我没有把它们贴在这里
<button
id="btn"
className="btn btn-primary"
onClick={() => this.handleClick(prod)}
>
然后将cartItems添加到状态中,并单击处理程序:
handleClick = (prod) => {
this.setState({
cartItems: [
...this.state.cartItems,
prod
],
});
.... // then use cartItems to pass it to api end-point
}