【发布时间】:2019-01-19 07:04:04
【问题描述】:
所以我正在做我的学校项目,建立一个电子商务网站。 我正在使用 reactjs、express 和 mysql。
问题是我正在设置我的产品输出渲染,通过使用 .map 函数,我使用 axios 从 mysql 获取 API。我的反应使用 .map 完全显示了产品,但是当我将它添加到我的购物车时,当我在我的 mysql 行中添加第一个产品时出现错误,但是当我在 mysql 行中添加第二个产品时结果是是正确的。所以我尝试添加第 3 个产品,然后第 1 个和第 2 个产品无法添加到购物车,只有第 3 个产品(最后一行)可以。
请有人帮我解决这个问题,我问了我的朋友,他们不知道出了什么问题,因为一切似乎都是正确的。
这是我的代码:
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的最后一个数组,不应该是这样的..
任何建议将不胜感激。 谢谢!
【问题讨论】:
-
它是因为您对所有地图项使用相同的 ref,第 1 项(三个输入元素)的 ref 与第 2 项和三个的 ref 相同,因此最后 ref 将具有第三项输入字段的引用。最好为 ref 使用一些唯一名称,例如:
ref={'idprods' + i}并将 i 传递给 buynow 方法并使用它来访问正确的 dom 元素:this.refs['idprods' + i].value -
@MayankShukla 谢谢先生,我这样做是因为它对我来说更容易......我使用我的 .map 函数中的索引来替换 i 并且它有效
标签: javascript mysql reactjs array.prototype.map