问题
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