javascript - I want to create a countdown watch in react, in which user puts in the input, probably in seconds and then it goes down to 0 -
this clock class. totally new react started yesterday , still don't have full grasp of state , props. thought componentdidmount()
react function keeps executing function in console see.it working not perfectly. start decrementing more should. thank you.
import react, {component} 'react'; import './app.css'; import './app'; class clock extends component{ constructor(props){ super(props); this.state = { seconds: 0, } console.log('this.props',this.props); } // componentwillmount(){ this.timer(this.props.time); } componentdidmount(){ setinterval(()=> this.timer(this.props.time),1000); } timer(time){ console.log('time in timer', time) let count = 0; time = time - setinterval(count++); this.setstate({seconds: time}); } render(){ return ( <div> <div classname="clock-seconds">{this.state.seconds} seconds</div> </div> ) } } export default clock;
my code in app.jsx looks this:
import react, {component} 'react'; import clock './clock'; import './app.css'; import {form, formcontrol, button} 'react-bootstrap'; class app extends component{ constructor(props){ super(props); this.state ={ time: '60', newtime: '' } } changetime(){ this.setstate({time: this.state.newtime}); } render(){ return ( <div classname="app"> <div classname = "app-title"> countdown {this.state.time} </div> <clock time={this.state.time} /> <form inline > <formcontrol classname="deadline-input" placeholder='new date' onchange={event => this.setstate({newtime: event.target.value})} /> <button onclick={() => this.changetime()}> submit </button> </form> </div> ) } } export default app;
i think problem line: time = time - setinterval(count++);
i'm not quite sure that's supposed do, here's how approach it:
constructor(props){ super(props); this.state = { seconds: null, // you'll want test null timerid: null // capture timer id can clear it. otherwise every time navigate away , component, create new timer. } console.log('this.props',this.props); } componentwillmount(){ //this.timer(this.props.time); // rid of altogether, it's not needed , should avoid willmount in favor of didmount } componentdidmount(){ this.settimer(); //setinterval(()=> this.timer(this.props.time),1000); } componentwillunmount() { clearinterval(this.state.timerid); } settimer() { const {time} = this.props; // set state props if isn't defined yet if (this.state.seconds === null) this.setstate({seconds: time}); // clear existing timer if there one, avoid memory leaks if (this.state && this.state.timerid) clearinterval(this.state.timerid); // define function run each 1 sec const tick = () => { this.setstate({ seconds: this.state.seconds-- }); }; // set interval , capture id can clear later const id = setinterval(tick, 1000); this.setstate({timerid: id}); }
note, haven't tested code points in right direction.
Comments
Post a Comment