簡體   English   中英

更改另一個組件時反應重新渲染組件

[英]React re-render component when another component is changed

我有兩個React源文件AB A在其render方法中這樣調用B

{this.state.classificationSelected
      ?
      <div>
      <B classification={this.props.categories[this.state.categoryIndex].classes[this.state.classificationIndex]} ref="B"/>
      </div>
      :
      null
    }

因此,如果選擇了AClassification組件,則渲染B

B ,我有以下基於A的Classification來計算一些值的方法:

getSingleChoiceAttributes: function() {
    var singleChoiceAttributes = [];
    for(let attribute of this.props.classification.attributes){
        if(attribute.attributeType == 'SingleChoice') {
            singleChoiceAttributes.push(attribute);
        }
    }
    return singleChoiceAttributes;
},

當前,我從B的ComponentWillMount方法調用此方法。

我希望每次更改A的分類時都可以執行此方法。 但是,目前僅在第一次選擇A的類別時才調用它。

每當AClassification (由this.state.classificationIndex表示)改變時,如何更改getSingleChoiceAttributes方法?

使用componentWillReceiveProps

void componentWillReceiveProps(
  object nextProps
)

組件接收新道具時調用。 初始渲染不調用此方法。

以此為契機,通過使用this.setState()更新狀態來調用render()之前對prop過渡做出反應。 可以通過this.props訪問舊的道具。 在此函數中調用this.setState()不會觸發其他渲染。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM