简体   繁体   中英

React re-render component when another component is changed

I have two React source files, A and B . A , in its render method, calls B like this:

{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.

In B , I have the following method which computes some values based on A's 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.

I would like this method to get executed every time A 's classification is changed. However, for now it is called only when A 's classification is first selected.

How can I make the getSingleChoiceAttributes method change every time A 's Classification (represented by this.state.classificationIndex ) is changed?

Use 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(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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