我正在用Product编写一个react.js组件,当单击该项目时,我希望增加实际产品的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,我总是将0视为浏览器中的inCartCount值。
发布于 2017-01-15 14:56:14
问题是您每次都在渲染中重新初始化产品,可能的解决方案:
在父级组件中:
<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);
}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);发布于 2017-01-15 14:04:40
你不能像你那样使用代码。要增加计数器,您应该使用this.state.counter,并在组件中使用此变量。因为每次更改this.state时,组件都会自动重新呈现并获取新的this.state。如果您只是手动更改该值,那么组件就不会重新呈现,而且您在页面上也看不到更改的值。但是,不要忘记在方法this.state = {counter: 0};中初始化getInitialState(),如下所示:
getInitialState() {
return { counter: 0 };
}并将其用于render方法或任何像this.state.counter这样的方法中。
发布于 2017-01-15 14:04:49
每次从道具中获取产品,这些道具是不可变的,永远不会更新,您在这里有两个选项:
https://stackoverflow.com/questions/41661876
复制相似问题