因此,我正在做我的学校项目,正在建立一个电子商务网站。 我正在使用reactjs,express和mysql。
问题是,我正在使用.map函数设置我的产品输出渲染,我正在使用axios从mysql获取API。我的React通过使用.map完全显示了产品,但是当我将其添加到购物车中时,在mysql行中添加第一个产品时出现了错误,但是当我在mysql行中添加第二个产品时却发现了错误是正确的。因此,我尝试添加第三个产品,然后无法将第一个和第二个产品添加到购物车,而只能添加第三个产品(最后一行)。
请有人帮我解决这个问题,我问我的朋友,他们不知道出什么问题了,因为一切似乎都正确。
这是我的代码:
class Products extends Component {
state = {
mappings: []
};
componentDidMount() {
axios.get("http://localhost:3210/product").then(x => {
this.setState({ mappings: x.data });
console.log(this.state.mappings);
});
}
buynow() {
axios
.post(
"http://localhost:3210/cart",
// console.log(this.refs.namaprod.value),
{
nama_product: this.refs.namaprod.value,
quantity: this.refs.quantity.value,
total_harga: this.refs.price.value * this.refs.quantity.value,
user_id: this.props.id_user,
status: "@cart",
product_id: this.refs.idprods.value
}
)
.then(y => {
alert("added to cart");
});
}
render() {
const produks = this.state.mappings.map((y, index) => {
var namaproduk = y.nama_product;
var descriptions = y.description;
var stocks = y.stock;
var price = y.harga;
var imggbr = y.img_src;
var id = y.id_product;
return (
<div className="col-lg-3">
<figure className="card card-product">
<div className="img-wrap">
<img src={imggbr} />
</div>
<figcaption className="info-wrap">
<h4 className="title">{namaproduk}</h4>
<p className="desc">{descriptions}</p>
<div className="rating-wrap">
<div className="label-rating">
only <strong>{stocks}</strong> kicks left
</div>
<input
className="quantity pull-right"
type="number"
placeholder="0"
ref="quantity"
min="0"
max={stocks}
required
/>
<input
className="text"
ref="idprods"
type="hidden"
value={id}
/>
<input
className="text"
ref="namaprod"
type="hidden"
value={namaproduk}
/>
<input
className="text"
ref="price"
type="hidden"
value={price}
/>
</div>
</figcaption>
<div className="bottom-wrap">
<i
className="btn btn-sm btn-primary float-right"
onClick={() => {
this.buynow();
}}
>
Order Now
</i>
<div className="price-wrap h5">
<span className="price-new">${price}</span>
</div>
</div>
</figure>
</div>
);
});
return (
<div>
<div className="ProductFolio">
<center>
<h2>Featured Products</h2>
</center>
</div>
<div className="row">{produks}</div>
</div>
);
}
}
令人困惑的是.map的值仅适用于mysql的最后一个数组,并非如此。
任何建议将不胜感激。 谢谢!
答案 0 :(得分:0)
为此,最好不要使用引用。这就是react docs所说的。
裁判有一些很好的用例:
- 管理焦点,文本选择或媒体播放。
- 触发 命令性动画。
- 与第三方DOM库集成。
避免将refs用于可以声明式完成的任何事情。
例如,与其将open()和close()方法暴露在 对话框组件,将isOpen属性传递给它。
相反,请使用state获取您的值。在.map
函数中,将项目的索引分配给按钮单击。当单击按钮时,它将把该值传递给Buynow,您可以在那里使用它。
onClick={() => {
this.buynow.bind(this, index);
}}
现在,在Buynow函数中,获取映射的数据并使用对象中的每个值。
buynow(index) {
const product = this.state. mappings[index];
axios
.post(
"http://localhost:3210/cart",
// console.log(this.refs.namaprod.value),
{
nama_product: product.name,
quantity: product.quantity,
total_harga: product.price * product.quantity,
user_id: this.props.id_user,
status: "@cart",
product_id: product.idprods
}
)
}
提示::在定义函数时使用camelCasing,例如名称函数或诸如buyNow,updateName等变量。