Example component "Unclean"

The Responsive Documents section of the component specification discusses keeping the render method clean and explains what that means.

I came across several situations where React throws an error because I am doing something inappropriate in render , but would like to know if there are situations where the component may be "unclean" but not cause an error.

Can someone provide an example of a component that does one or more of the following without causing an error in React?

  • changes the state of a component in render (or somewhere else shouldn't)
  • reads or writes to the DOM when it should not
  • does not return the same result every time it is called / displayed
  • (possibly the same as the previous one): does not display the same DOM for the same details and states
+5
source share
1 answer

Pretend it's all in the render.

"changes the state of the component in the render (or somewhere else shouldn't)"

 this.state.foo = whatever; 

"reads or writes to the DOM when it should not"

 if (this.isMounted()) { this.getDOMNode().textContent = whatever }; document.querySelector('title').textContent = whatever; 

"does not return the same result every time it is called / displayed

 return <div>{Math.random()}</div> 

"(possibly the same as the previous one): does not display the same DOM for the same details and state"

 if (new Date().getHours()>=9 && new Date().getHours()<=12+5) { return <div>{this.props.fortune}</div> } else { return <div>I'm off the clock</div> } 

You mentioned the last example specifically in the commentary, so the right way to handle the time is to get the time in getInitialState and then set a timeout in componentDidMount when changing the time will affect rendering and setState. Thus, your interface will be synchronized with the world.

The naive solution is to just set Interval for a few seconds, which is fine until you have time to optimize it. The real solution here would be something like

 var now = Date.now(), closing = new Date(); closing.setHours(12+5, 0, 0, 0), opening = new Date(); opening.setHours(9, 0, 0, 0), delay; // past closing if (now > closing || now < opening) { if (opening < now) { opening.setHours(9+24); } delay = opening - now; } // currently open else { delay = closing - now; } setTimeout(delay, updateStateWithTime); 

And, like any change in state over time, mixins are often a good way to abstract and reuse.

+6
source

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


All Articles