简体   繁体   中英

how to call a function after completion of setting of group of state variables of functional component in reactjs

function check(){
const [variable, setvariable1] = useState(0);
const [variable2, setvariable2] = useState(0);
const [variable3, setvariable3] = useState(0);

const last_func = () => {
console.log("call this function")
}

const mainfunction = () =>{
setvariable(1);
setvariable2(1);
setvariable3(1);
last_func(); //this function needs to be called after completing above all state variables
}
}

i want call the last_func after completing the setting of all state variables to 1 then only i have to call that last_func

const mainfunction = () =>{
 setvariable(1);
 setvariable2(1);
 setvariable3(1);

 if(variable !== 0 && variable2 !== 0 && variable3 !== 0) last_func()

 //or if you know that variables will be equal to 1
 if(variable === 1 && variable2 === 1 && variable3 === 1) last_func()
}

also if you want to run last_fun automatically after all variables are >0 you can use useEffect:

useEffect(()=>{
mainfunction();
}, [variable, variable2, variable3])

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