【发布时间】:2016-09-18 15:36:50
【问题描述】:
我有以下组件,其中将显示产品列表。 CounterComponent 在两个地方添加,一个在 ProductCatalog 中,另一个在 ProductCard 中,可以在模态中显示。在柜台表示订购的商品的件数。 我想在更新时同步这两个计数器。在每个计数器状态更改上使用 forceUpdate 并不能解决问题。
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>
);
}
}
【问题讨论】:
-
您能否发布您的 CounterComponent 的代码?通常你不需要使用
forceUpdate,因为你的组件应该在你为props传递新值时简单地重新渲染。 IMO 将 onCountChanged 传递给 CounterComponent 也有点奇怪,因为您知道计数器值何时直接在父级中更改,所以在我看来 CounterComponent 不需要知道当它更改时要做什么,作为父级可以处理。
标签: javascript reactjs reactjs-flux