繁体   English   中英

通过单击react.js增加数量

[英]Increase number by click in react.js

我正在react.js编写一个Product组件,并且当单击该项目时,我想增加实际产品的inCartCount值。

import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Product.css';

var NumberFormat = require('react-number-format');
class Product extends React.Component {

    addToCart(product) {
        console.log(product.inCartCount);
        product.inCartCount++;
    }

    render() {

        const product = this.props.data;

        product.inCartCount = product.inCartCount || 0;

        return (
            <div onClick={this.addToCart.bind(this, product)}>
                <h3>{product.name}</h3>
                <NumberFormat value={product.price} displayType={'text'} thousandSeparator={true} suffix={' Ft'}/>
                <span>{product.inCartCount}</span>
            </div>
        );
    }
}

export default withStyles(s)(Product);

console.log该值正在增加,但未呈现为DOM ,我始终在浏览器inCartCount值视为0

您不能像使用代码那样使用代码。 要增加计数器,您应该使用this.state.counter并在您的组件中使用此变量。 因为每次this.state更改时,您的组件都会自动重新呈现并采用新的this.state 如果您只是手动更改值,您将执行此操作-组件不会重新呈现,并且您永远不会在页面上看到更改后的值。 但是不要忘记this.state = {counter: 0}; 首先在方法getInitialState()这样的:

  getInitialState() {
    return { counter: 0 };
  }

并将其用于render方法或类似this.state.counter任何方法

每次从道具获取产品都是不可变的,并且永远不会更新,这里有2个选项:

  1. 使用新计数更新父级,并将其状态设置为更新产品,这将使用新产品道具重新渲染子级并具有新计数
  2. 使用父项的道具初始化状​​态,然后您控制产品的状态,在这种情况下,您需要在更新计数以重新呈现后将状态设置为新产品

问题是您每次都在渲染中重新初始化产品,可能的解决方案:

  1. 用新计数更新父组件,将函数从父传递给子。

在父组件中:

<Product
    updateProduct={this.updateProduct.bind(this)}
    data={this.state.data}    
/>

updateProduct(value){
    this.setState({data:value});
}

在子组件中:

addToCart(product) {
    console.log(product.inCartCount);
    product.inCartCount++;
    this.props.updateProduct(product);
}

2.将产品以状态存储在子组件上,如下所示:

import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Product.css';

var NumberFormat = require('react-number-format');

class Product extends React.Component {
     constructor(props) {
       super(props);
       this.state = {
         product: props.data
       };
     }  

    addToCart() {
       let product = this.state.product;
       product.inCartCount = product.inCartCount ? product.inCartCount+1 : 1;
       this.setState({product});
    } 

    render() {
       return (
          <div onClick={this.addToCart.bind(this)}>
              <h3>{this.state.product.name}</h3>
              <NumberFormat value={this.state.product.price} displayType={'text'} thousandSeparator={true} suffix={' Ft'}/>
              <span>{this.state.product.inCartCount}</span>
          </div>
       );
    }
}

export default withStyles(s)(Product);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM