我该如何做到这一点,以便数据仅将阵列中的一项发送到购物车
我正在尝试在按钮单击中将特定项目添加到购物车(位于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);
};
}
- 增加,减少和删除工作正常,这就是为什么我没有在这里发布它们
I'm trying to add the particular item in cart (which is located at react-db.json file) on button click, and later display it on a different page. Also if anyone has a simpler way of doing this it would be really helpfull
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);
};
}
note - increment, decrement and delete are working fine that's why i didn't post them here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
然后将Cartitems添加到状态中,然后在单击处理程序中:
Then add cartItems into state, and in click handler :