首页 > 解决方案 > 反应增量和减量计数

问题描述

import {
  ProductCycleContextProvider,
  ProductContext,
} from '../contexts/productCycleContext';
class Cart extends Component {
  static contextType = ProductContext;
  constructor(props) {
    super(props);
    this.state = {
      selectedForCart: [],
      checkOut: true,
      grandTotal: undefined,
    };
  }

  async componentDidMount() {
    await axios
      .get('http://localhost:80/newItem/storeIntoCart')
      .then((res) => {
        res.data.map((i) => {
          this.context.setCart(i);
        });
      })
      .catch((e) => alert(e));
  }
  remove = () => {
    console.log('remove');
  };
  increment = (v, i) => {
    axios
      .patch(`http://localhost:80/cart/cartCustomize/${i}`, {
        quantity: v,
      })
      .then((res) => {
        const ind = this.context.cart.findIndex((x) => x._id === res.data._id);
        this.context.cart[ind] = res.data;
      })
      .catch((e) => console.log(e));
  };
  decrement = (v, i) => {};
  render() {
    return (
      <div>
        {this.context.cart &&
          this.context.cart.map((v, i) => {
            return (
              <Container className="mt-5" key={i}>
                <Row>
                  <Col lg={2} md={2} sm={12}>
                    <h5>
                      <b>{v.title}</b>
                    </h5>

                    <img
                      src={v.photo}
                      style={{
                        border: '2px solid black',
                        borderRadius: '5px',
                        width: '100px',
                        height: '80px',
                      }}
                    />
                  </Col>
                  <Col lg={2} md={2} sm={12}>
                    <p>
                      Price:&emsp;&#8377;
                      {v.priceTaxIncluded}
                    </p>
                    <p style={{fontSize: '10px'}}>Tax inclusive</p>
                  </Col>

                  <Col lg={2} md={2} sm={12}>
                    <Row>
                      <Button
                        value={v.quantity}
                        onClick={(e) => {
                          const val = e.target.value;
                          const id = v._id;

                          this.decrement(val, id);
                        }}>
                        -
                      </Button>
                      {v.quantity}
                      <Button
                        value={v.quantity}
                        onClick={(e) => {
                          const id = v._id;
                          let val = Number(e.target.value);
                          let q = val + 1;
                          this.increment(q, id);
                        }}>
                        +
                      </Button>
                    </Row>
                  </Col>
                  <Col lg={2} md={2} sm={12}>
                    <br></br>
                    <Button
                      className="btn btn-warning mt-2"
                      size="sm"
                      onClick={this.remove}>
                      Remove
                    </Button>
                  </Col>
                  <Col lg={2} md={2} sm={12}>
                    {this.state.checkOut && (
                      <>
                        <p>{v.priceTaxIncluded * v.quantity}</p>
                      </>
                    )}
                  </Col>
                  <Col lg={2} md={2} sm={12}></Col>
                </Row>
              </Container>
            );
          })}
      </div>
    );
  }
}

在此代码中,单击增量时,我需要将产品数量加一。这个数量应该乘以价格。它正在发生,但如果我第一次增加,那么它不会显示任何内容,第二次它增加并显示以前的值,第三次点击它显示第二次点击的值......就像它一样。 ..我应该单击增量按钮 2 次 我应该使用组件确实更新...但是第一次渲染它?

标签: javascriptreactjsreact-component

解决方案


ProductContext如果手动更新,则不应更新购物车属性。而是使用ProductContext其中的一个函数setState来通知 React 状态的变化。

  increment = (v, i) => {
    axios
      .patch(`http://localhost:80/cart/cartCustomize/${i}`, {
        quantity: v,
      })
      .then((res) => {
        this.context.setCartItem(res.data);
      })
      .catch((e) => console.log(e));
  };

在您的提供者/上下文中:

setCartItem(cartItem) {
  const ind = this.state.cart.findIndex((x) => x._id === cartItem._id);
  const updatedCart = [...this.state.cart][ind] = cartItem;

  this.setState(updatedCart);
}

推荐阅读