嵌套组件中的 forceUpdate
forceUpdate in nested components
我有以下组件,其中将显示产品列表。 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>
);
}
}
在这种情况下很可能不需要 Forceupdate。任何反应组件只需要在状态改变或道具改变时重新渲染。
React 会自动处理这个问题。
你的情况:
- 将您的产品数量作为道具传递给
<ProductCart>
- 或者将计数保存在状态中。
在你的情况下:似乎父级已经知道产品数量,因为你正在调用一个函数来检索它。
最好将产品计数作为 props 传递,而不是调用方法来检索计数。
我有以下组件,其中将显示产品列表。 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>
);
}
}
在这种情况下很可能不需要 Forceupdate。任何反应组件只需要在状态改变或道具改变时重新渲染。
React 会自动处理这个问题。
你的情况:
- 将您的产品数量作为道具传递给
<ProductCart>
- 或者将计数保存在状态中。
在你的情况下:似乎父级已经知道产品数量,因为你正在调用一个函数来检索它。
最好将产品计数作为 props 传递,而不是调用方法来检索计数。