Reputation: 943
I am having following component in which a list of products will be displayed. the CounterComponent is added in two places, one in ProductCatalog and the other one in ProductCard which can be shown i a modal. I display the number of ordered product in counter. I want to synchronize these two counters as one is updated. using forceUpdate on each of the counter state change doesn't do the trick.
export default class ProductCatalog extends Component {
showProductCard(product){
var scope = this;
$('.ui.modal.' + product.code)
.modal({
onHide: function(){
scope.forceUpdate();
}
}).modal('show');
}
render() {
var scope = this;
return (
<div className="ui grid" id="productCatalog">
{
this.props.products.map(function(raw) {
return (
<div className="product" onClick={scope.showProductCard.bind(scope, product)}></div>
<div className="extra content">
<CounterComponent
count={scope.props.getProductCount(product)}
product={product}
onCountChanged={scope.props.onCountChanged}>
</CounterComponent>
<ProductCard
count={scope.props.getProductCount(product)}
product={product}
onCountChanged={scope.props.onCountChanged}>
</ProductCard>
</div>
);
})
}
</div>
);
}
}
Upvotes: 1
Views: 509
Reputation: 14101
Forceupdate is most likely not needed in this case. Any react component only should need a rerender when state changes or when props change.
And react handles this automatically.
In your case:
<ProductCart>
In your case: it seems like the parent already knows the product count, since you are calling a function to retrieve it.
Better to pass the product count as props, instead of calling a method to retrieve the count.
Upvotes: 2