React.js, wait for setState to finish before triggering a function?

前端 未结 5 725
庸人自扰
庸人自扰 2020-12-23 08:31

Here\'s my situation:

  • on this.handleFormSubmit() I am executing this.setState()
  • inside this.handleFormSubmit(), I am calling this.findRoutes(); - whic
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-23 09:23

    setState() has an optional callback parameter that you can use for this. You only need to change your code slightly, to this:

    // Form Input
    this.setState(
      {
        originId: input.originId,
        destinationId: input.destinationId,
        radius: input.radius,
        search: input.search
      },
      this.findRoutes         // here is where you put the callback
    );
    

    Notice the call to findRoutes is now inside the setState() call, as the second parameter.
    Without () because you are passing the function.

提交回复
热议问题