Why do I have two different values on this boolean in React Native? [duplicate]

杀马特。学长 韩版系。学妹 提交于 2020-02-06 03:42:35

问题


In the React Native App, after I click the toggle button, the function _toggleServerSwitch gets triggered. Then I change the state serverSwitchValue to the same value as x.

Expected: serverSwitchValue and x should have the same value when console.log().

Actual: When console.log(), the two variables have different values.

It seems that the program works, but at the time when console.log() gets triggered, the values are not the same. Why?

const [serverSwitchValue, setServerSwitchValue] = useState(false);

  const _toggleServerSwitch = x => {
    setServerSwitchValue(x);
    console.log('x is: ' + x);
    console.log('serverSwitchValue is: ' + serverSwitchValue);
  };

回答1:


setServerSwitchValue() is an async function , so it doesnt imply that you will get the values updated instantly. YOu can use useEffect as below :

useEffect(() => {
 console.log(serverSwitchValue);
}, [serverSwitchValue]); // Only re-run the effect if open changes

Hope it helps.



来源:https://stackoverflow.com/questions/59730836/why-do-i-have-two-different-values-on-this-boolean-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!