简体   繁体   中英

Force React component update after async function?

I have the following piece of code in my react component:

onSubmit(e) {
      e.preventDefault();
      this.props.doSomething();

      this.setState({
          inputField: this.props.myReducer.someValue
      });
  }

So, everytime somebody presses the 'Submit' button, some function is executed, then the state of my input field gets updated with the according value that changed in 'myReducer'.

However, there is a problem. 'doFunction' is an async action, which means that setting the state straight afterwards results in no update, since the state will not yet have changed by the function when it is set right afterwards.

How would I handle something like this in react/redux?

It has to do with the nature of doSomething() . You should always get notified that the function is done. 99% of the time, the something is an Ajax call, which in most libraries, returns a promise:

 this.props.doSomething()
   .then(() => 
          this.setState({
            inputField: this.props.myReducer.someValue
          });

If doSomething() does not return a promise, you should probably edit it or augment it so it does return a promise. If it takes a callback, you can just do this:

 new Promise(this.props.doSomething)
   .then(() => 
          this.setState({
            inputField: this.props.myReducer.someValue
          });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM