简体   繁体   中英

React native variable not update inside function

  const [businessHour, setBusinessHour] = useState("");
 const getHour = () => {
   console.log(businessHour);
}

setBusinessHour('1234');
getHour();

The result show "" instead of "1234", any way to update the variable? Thank you

please update your entire code of a component. The result will show empty string "" first, and then when state is changed, it will print "1234" . so there will be multiple logging instead of just one.

I faced the same problem earlier. My workaround is to create a temporary variable to use because the state has not updated yet.

const [businessHour, setBusinessHour] = useState("");
 const getHour = (businessHour) => {
   console.log(businessHour);
}

let newBusinessHour = '1234'
setBusinessHour(newBusinessHour);
getHour(newBusinessHour);

A better way to do is, use the useEffect callback:

const [businessHour, setBusinessHour] = useState("");

useEffect(() => {
getHour()
},[getHour])

 const getHour = useCallback(() => {
   console.log(businessHour);
},[businessHour])

setBusinessHour('1234');

so here basically useEffect will be called whenever getHour changes which is dependent on businessHour

Hope it helps.

You can update state if you want to update some views followed by that state. In the case above, you don't need to update state.

businessHour = '1234';
getHour();

Then you will get the result you want.

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