简体   繁体   中英

Function step by step in one Click in react

I use ReacJs and Redux in my project and have a sitoation where i need to click only one time and function have to run 2 inside functions step by step. 2nd function cant run before ended func2. How can I do this function only in one click on mainfunc()? Need a example code please.

func1()

func2()

mainfunc(){
 func1()
 func2()
}

So you have a many options in React to achieve a goal, there is no one way to do something.

Here are a couple of example:

  1. using async events (API calls, promises etc...)

 // async export const MyComponent = () => { const eventOne = async () => { return new Promise((resolve, reject) => { resolve(true); }) } const eventTwo = async () => { return new Promise((resolve, reject) => { resolve(true); }) } const handleClick = async () => { await eventOne(); await eventTwo(); } return ( <button onClick={handleClick}> Click me </button> ) };

So Here we are just taking two async events and waiting for each one to finish before moving onto the next using async/await.

Another approach might be to utilise state , in which case you could do something like this:

 import { useState, useEffect } from 'react'; // state export const MyComponent = () => { const [eventOneHasHappened, setEventOneHasHappened] = useState(false); const triggerEventOne = () => { // do something setEventOneHasHappened(true); } const triggerEventTwo = () => { // do something } useEffect(() => { if (eventOneHasHappened) { triggerEventTwo(); } }, [eventOneHasHappened]); const handleClick = () => { triggerEventOne(); } return ( <button onClick={handleClick}> Click me </button> ) };

There are many more ways to do something like this depending if your using async or not but try to get used to React hooks, they're very useful

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