javascript - React, React-Router and setInterval -
i have component state wish regularly update timing function, therefore have following code:
componentdidmount() { console.log("stage.componentdidmount") // var self = this; if (this.timer == null) { console.log("create timer") var timerfunction = function() { console.log(this.timer); }.bind(this) this.timer = setinterval(timerfunction, 1000); } } componentwillunmount() { console.log("component unmount") clearinterval(this.timer) } the problem comes in when refresh route subcomponent subcomponent. notice parent of component renders twice, , therefore components constructor , componentdidmount called twice. creates 2 timers, , timing invocations of twice numerous!
while isn't problem when navigating route , navigating away, componentdidmount , componentwillunmount calls balance each other out, problem when refreshing reason described.
is there sort of balancing function or way prevent route's subcomponent (the 1 creating timer in componentdidmount shown in code sample) creating more 1 timer?
here root file, setups of routing , renders "renderer" contains subcomponent constructor called twice.
import react 'react'; import reactdom 'react-dom'; import {browserrouter router, route } 'react-router-dom' import './styles.css'; const navlink = require( 'react-router-dom' ).navlink import renderer './renderer/renderer' import rootcomponent './componentsscratchpad/rootcomponent' function nav() { return ( <ul classname='nav'> <li><navlink activeclassname="active" exact to='/componentsscratchpad'>scratch pad</navlink></li> <li><navlink activeclassname="active" exact to='/renderer'>renderer</navlink></li> </ul> ) } class app extends react.component { render() { return ( <router> <div> <nav /> <route exact path='/renderer' render={ () => <renderer /> } /> <route exact path="/componentsscratchpad" render={ () => <rootcomponent /> }/> </div> </router> ) } } reactdom.render(<app />, document.getelementbyid('root'))
Comments
Post a Comment