【问题标题】:forceUpdate in nested components嵌套组件中的 forceUpdate
【发布时间】: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


【解决方案1】:

在这种情况下很可能不需要强制更新。任何 React 组件仅在状态更改或道具更改时才需要重新渲染。
react 会自动处理这个问题。

在你的情况下:

  • 要么将您的产品计数作为道具传递给&lt;ProductCart&gt;
  • 或将计数保存在状态中。

在您的情况下:似乎父母已经知道产品数量,因为您正在调用一个函数来检索它。

最好将产品计数作为道具传递,而不是调用方法来检索计数。

【讨论】:

    猜你喜欢
    • 2017-12-31
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2018-03-22
    相关资源
    最近更新 更多