简体   繁体   English

更改另一个组件时反应重新渲染组件

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

I have two React source files, A and B . 我有两个React源文件AB A , in its render method, calls B like this: A在其render方法中这样调用B

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

So B is rendered if the Classification component of A is selected. 因此,如果选择了AClassification组件,则渲染B

In B , I have the following method which computes some values based on A's Classification : B ,我有以下基于A的Classification来计算一些值的方法:

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

Currently, I am calling this method from B's ComponentWillMount method. 当前,我从B的ComponentWillMount方法调用此方法。

I would like this method to get executed every time A 's classification is changed. 我希望每次更改A的分类时都可以执行此方法。 However, for now it is called only when A 's classification is first selected. 但是,目前仅在第一次选择A的类别时才调用它。

How can I make the getSingleChoiceAttributes method change every time A 's Classification (represented by this.state.classificationIndex ) is changed? 每当AClassification (由this.state.classificationIndex表示)改变时,如何更改getSingleChoiceAttributes方法?

Use componentWillReceiveProps . 使用componentWillReceiveProps

void componentWillReceiveProps(
  object nextProps
)

Invoked when a component is receiving new props. 组件接收新道具时调用。 This method is not called for the initial render. 初始渲染不调用此方法。

Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). 以此为契机,通过使用this.setState()更新状态来调用render()之前对prop过渡做出反应。 The old props can be accessed via this.props. 可以通过this.props访问旧的道具。 Calling this.setState() within this function will not trigger an additional render. 在此函数中调用this.setState()不会触发其他渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM