【问题标题】:React increment and decrement count反应增量和减量计数
【发布时间】:2020-10-09 07:42:45
【问题描述】:
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 次​​strong>我应该使用组件确实更新...但是第一次渲染它?

【问题讨论】:

    标签: javascript reactjs react-component


    【解决方案1】:

    如果 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);
    }
    

    【讨论】:

    • 先生,我只是这样做了。我的状态对象是“cart”,函数是 setCart()
    • 对不起,我不明白你想说什么。
    • 我确实喜欢你已经说过的...使用函数设置状态。在提供者中
    猜你喜欢
    • 2020-03-14
    • 2018-09-02
    • 2022-01-10
    • 2017-10-30
    • 2021-06-07
    • 2012-03-27
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多