反应事件处理程序:尝试更新购物车数量“的onChange”使用默认值

问题描述 投票:0回答:1

我有正确构建我的逻辑问题。

我有两个事件处理程序: - 在onChange标签越来越theQty(selectedQty<select>。 - onClick用于发送productID和编目组分(如JSON)(产物组分的父组件)的数量

问题:我可以发送数量和productID只有当选择数量,它不会发送1默认selectedQty到目录组件(发送未定义)(因为我的代码的结构onChange事件处理程序的方式已被用于发射数量被选择。

问:我怎样才能送1的默认数量,而不必选择它(并因此不必触发onItemQtySelected处理用户?

Product.jsx

import React, { Component } from "react";
import Stock from "../modules/stock";

class Product extends Component {
  state = {
    itemsToSendToCart: {}
  };
  componentDidMount() {}

  onItemQtySelected = event => {
    var select = event.target;
    var selectedOption = select.options[select.selectedIndex];

    const productID = selectedOption.getAttribute("name");

    let selectedQty = event.target.value;

    console.log("selected qty...", selectedQty);

    const itemToCart = this.state.itemsToSendToCart;

    itemToCart.productID = productID;
    if (selectedQty !== 1 || selectedQty < 0) {
      selectedQty = 1;
    }
    itemToCart.selectedQty = selectedQty;

    this.setState({ itemsAddedToCart: itemToCart });
  };
  renderQtyElement() {
    const { productQtyInStock } = this.props;
    let arrayOfOptions = [];
    let count = 1;
    while (count <= productQtyInStock) {
      arrayOfOptions.push(count);
      count++;
    }
    return arrayOfOptions;
  }

  render() {
    const {
      productID,
      productName,
      productPrice,
      productDesc,
      productCategory
    } = this.props;

    // Get the items selected to cart properties and send when add to cart event is clicked
    const itemsInCart = this.state.itemsToSendToCart;

    return (
      <React.Fragment>
        <p>{this.state.productId}</p>
        <div key={productID} className="card" style={{ marginRight: 0 }}>
          <img
            className="card-img-top"
            src="https://sc01.alicdn.com/kf/UT8f0GFXOJbXXagOFbXG/Soccer-Balls-Pakistan.jpg"
            alt="Card image cap"
          />
          <div className="card-body">
            <h5 className="card-title">Name: {productName}</h5>
            <p className="card-text">Description: {productDesc}</p>
            <p className="card-text">Price: {productPrice}</p>
            <p className="card-text">
              <label>Qty:</label>
              <select onChange={this.onItemQtySelected}> <----
                {this.renderQtyElement().map(qty => (
                  <option key={qty} name={productID}>
                    {qty}
                  </option>
                ))}
              </select>
            </p>
            <p className="card-text">Category: {productCategory}</p>
            <button
              href="#"
              // send to cart component via params? instead of catalogue
              onClick={() => this.props.onAddToCart(itemsInCart)} <-----
              className="btn btn-primary"
            >
              Add To Cart
            </button>
          </div>
        </div>
      </React.Fragment>
    );
  }
}

export default Product;

catalogue.jsx

import React, { Component } from "react";
import Stock from "../modules/stock";
import Product from "./product";

class Catalogue extends Component {
  state = {
    items: [],
    itemsForCart: []
  };

  async componentDidMount() {
    const inventory = await Stock.initStock();
    if (inventory) {
      const items = inventory.map(item => item);

      this.setState({ items });
      console.log(" state >>", this.state.items);
    }
  }

  handleAddToCart = ({ productID, productQty }) => {
    // if (productQty <= 0 && productQty !== 1) return (productQty = 1);
    let item = { productID, productQty };
    let updatedItemsForCart = [];

    let totalItems = this.state.itemsForCart;
    // add previous items in the updated state property
    // totalItems.map(existingItems => updatedItemsForCart.push(existingItems));
    // add the newest item added to cart
    if (item.productQty <= 0) item.productQty = 1;
    updatedItemsForCart.push(...totalItems, item);
    // set state
    this.setState({ itemsForCart: updatedItemsForCart });
  };

  render() {
    console.log("items In cart", this.state.itemsForCart);
    // console.log("updated cart length", h);

    return (
      <React.Fragment>
        <h1>Catalogue...</h1>
        <div>
          {this.state.items.map(item => (
            <Product
              key={item.productID}
              productID={item.productID}
              productName={item.productName}
              productPrice={item.productPrice}
              productQtyInStock={item.productQty}
              productDesc={item.productDesc}
              productCategory={item.productCategory}
              onAddToCart={this.handleAddToCart}
            />
          ))}
        </div>
      </React.Fragment>
    );
  }
}

export default Catalogue;
javascript reactjs onclick onchange cart
1个回答
0
投票

试着增加值在初始化的状态。

constructor(props) {
    super(props);
    this.state = {
        itemsToSendToCart: {},
        itemsAddedToCart: { selectedQty: 1 }
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.