84738

How to change a react state immediately by setTimeout after setState?

Question:

new in react here, don't know if it's right to do this on the setState callback like this?

setTimeout(()=> { this.setState((state, props) => ({ activateLightColorForRed: true }), () => { setTimeout(()=> { this.setState(()=> ({ activateLightColorForRed: false })) }, 500); red.play(); }) }, toWait);

or maybe something like this?

this.setState((state, props) => { this.setState((state, props) => { activateLightColorForRed: true }); setTimeout(() => { activateLightColorForRed: false },500) })

are the state on the setState callback updated? something weird is happening in my components, it's rendering multiple times. I am not sure but I think it's because I'm doing the first sample?

Answer1:

Your question does not seem to follow the pattern of a regular react app. You should be using the lifecycle events to <em>react</em> to the state being changed. You should not be making multiple, nested, confusing callbacks (like it seems you want to do).

Might I suggest a structure more like this

<pre class="snippet-code-js lang-js prettyprint-override">class Foo extends React.Component { constructor(props) { super(props); this.state = { activateLightColorForRed: false, }; } componentDidUpdate(prevProps, prevState) { if (this.state.activateLightColorForRed) { // when the state is updated (turned red), // a timeout is triggered to switch it back off this.turnOffRedTimeout = setTimeout(() => { this.setState(() => ({activateLightColorForRed: false})) }, 500); } } componentWillUnmount() { // we set the timeout to this.turnOffRedTimeout so that we can // clean it up when the component is unmounted. // otherwise you could get your app trying to modify the state on an // unmounted component, which will throw an error clearTimeout(this.turnOffRedTimeout); } render () { // really simply ui to show how it *could* work return ( <div onClick={this.turnLightRed}> The light is {this.state.activateLightColorForRed ? "Red" : "Green"}. <br /> Click to change! </div> ) } turnLightRed = () => { // this function will turn the light red this.setState(() => ({ activateLightColorForRed: true })); } } ReactDOM.render( <Foo name="World" />, document.getElementById('container') ); <pre class="snippet-code-html lang-html prettyprint-override"><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script> <div id="container"></div>

Hope that helps.

Recommend

  • XPages: Dynamically populate Navigator Control
  • Substring domainname from URL SQL
  • How to display CollectionViewCell in center in swift 4
  • Apache Camel inOut routes, out exchange marshaling/unmarshaling with jaxb
  • es6 Javascript class using this inside a callback [duplicate]
  • can i initialize an array outside the method just like we initialize a member/field variable
  • Splitting a csv file into panda dataframe by multiple columns
  • How to upload video to Vimeo through their api?
  • Android Get the markers that are not clustered
  • Why do native C++ projects have a TargetFrameworkVersion?
  • how to reopen a class in gems
  • 'Resource exhausted' memory error when trying to train a Keras model
  • Weird LEFT OUTER JOIN on Includes eager loading of rails 3
  • Get rendered html code in Backing Component from Composite Component
  • Rails redirect_to another controller method throwing “Template missing”
  • How to access recipient on sent messages page with mailboxer
  • Raphael.js function getBBox give back NAN/NAN/NAN in IE8
  • matching similar elements in between two lists
  • Vuejs: Lifecycle hooks of child routerview components using keep alive
  • IE10 strips out hashtag from the URL
  • Create a link to a web page that runs a Javascript function on the page
  • Two Tables Serving as one Model in Rails
  • What causes the runtime difference in this trivial fortran code?
  • Sensibility of combined Maven/Ant+Ivy build management for dual platform Desktop/Android deployment?
  • Bootstrap (v3.3.4) glyphicons not displayed in IE when refresh page (F5)
  • Redshift Querying: error xx000 disk full redshift
  • Pycharm: Marking a folder as 'sources root' is not recursive for subfolders
  • npm 5.4.1 install/uninstall all failing
  • Laravel: Getting Session ID oddly truncates when using foreach
  • How to disable all widgets inside Panel or inside Composite?
  • Reduction and collapse clauses in OMP have some confusing points
  • Saving Changes After In-App Purchase Has Been Purchased
  • Rails Find when some params will be blank
  • Deselecting radio buttons while keeping the View Model in synch
  • req.body is undefined - nodejs
  • Symfony2: How to get request parameter
  • How can I estimate amount of memory left with calling System.gc()?
  • Akka Routing: Reply's send to router ends up as dead letters
  • Is there a mandatory requirement to switch app.yaml?
  • Unable to use reactive element in my shiny app