【问题标题】:Reactjs , .map function output variables errorReactjs,.map函数输出变量错误
【发布时间】: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


【解决方案1】:

为此使用 refs 不是最佳做法。这是 react 文档所说的。

refs 有几个很好的用例:

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

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

例如,而不是公开 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
      }
    )
}

提示:在定义函数时使用驼峰命名法,例如名称函数或变量,如 buyNow、updateName 等。

【讨论】:

  • 感谢您的回复,但至于您编写的代码我真的无法使用,因为需要引用操作的数量...但是这段代码很棒,看看我是否会使用这个将来..感谢您的提示:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多