首页 > 解决方案 > Reactjs,.map函数输出变量错误

问题描述

所以我正在做我的学校项目,建立一个电子商务网站。我正在使用 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 的最后一个数组,它不应该是这样的..

任何建议将被认真考虑。谢谢!

标签: javascriptmysqlreactjsarray.prototype.map

解决方案


为此使用 refs 不是最佳实践。这是反应文档所说的。

refs 有一些很好的用例:

  • 管理焦点、文本选择或媒体播放。
  • 触发命令式动画。
  • 与第三方 DOM 库集成。

避免将 refs 用于任何可以以声明方式完成的事情。

例如,不要在 Dialog 组件上公开 open() 和 close() 方法,而是将 isOpen 属性传递给它。

相反,使用状态来获取您的值。在您的.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 等。


推荐阅读