javascript - How to change a react state immediately by setTimeout after setState? -
new in react here, don't know if it's right on setstate callback this?
settimeout(()=> { this.setstate((state, props) => ({ activatelightcolorforred: true }), () => { settimeout(()=> { this.setstate(()=> ({ activatelightcolorforred: false })) }, 500); red.play(); }) }, towait);
or maybe this?
this.setstate((state, props) => { this.setstate((state, props) => { activatelightcolorforred: true }); settimeout(() => { activatelightcolorforred: false },500) })
are state on setstate callback updated? weird happening in components, it's rendering multiple times. not sure think it's because i'm doing first sample?
your question not seem follow pattern of regular react app. should using lifecycle events react state being changed. should not making multiple, nested, confusing callbacks (like seems want do).
might suggest structure more this
class foo extends component { constructor(props) { super(props); this.state = { activatelightcolorforred: false, }; this.turnlightred = () => { // function turn light red this.setstate(() => ({ activatelightcolorforred: true }); } } componentdidupdate(nextprops, nextstate) { if (nextstate.activatelightcolorforred) { // when state updated (turned red), // timeout triggered switch off this.turnoffredtimeout = settimeout(() => { this.setstate(() => ({activatelightcolorforred: false}) }, 500); } } componentwillunmount() { // set timeout this.turnoffredtimeout can // clean when component unmounted. // otherwise app trying modify state on // unmounted component, throw error cleartimeout(this.turnoffredtimeout); } render () { // ui show how *could* work return ( <div onclick={this.turnlightred}> light {this.state.activatelightcolorforred ? "red" : "green"}. <br /> click change! </div> ) } }
hope helps.
Comments
Post a Comment