How to distinguish what caused the rendering of the React component: something inside or outside the component?

I have two nested reactive components: Outerand Inner. Whenever I call setStatefrom Inner, the renderinner component is called. In addition, whenever I call setStatean external component, the functions of renderboth the external and internal components are called. I would like to highlight these two cases and determine what a piece of rendering of the internal component is. My function render Innershould behave differently depending on this. How can i do this?

+4
source share
2 answers

You can use the fact that componentWillReceiveProps is called only when the component receives new details (here you can find: http://busypeoples.imtqy.com/post/react-component-lifecycle/ ), and not when calling setState, and , which is important, they do not even have to be different details than the existing ones (for https://facebook.imtqy.com/react/docs/component-specs.html#updating-componentwillreceiveprops ). Therefore, you should be able to do something in accordance with

componentWillReceiveProps() {
  this.setState({parentUpdated: true});
}

render() {
  if (this.state.parentUpdated) {
    // Render one way
  } else {
    // Render the other way
  }
}

Although you will also need to disable this after rendering, or just make sure that every call to this.setState also includes {parentUpdated: false}.

+1
source

Update Inner . componentWillUpdate doc Inner Outer.

0

Source: https://habr.com/ru/post/1648709/


All Articles