为什么我在 React Native 中的这个布尔值上有两个不同的值?
在 React Native App 中,点击切换按钮后,_toggleServerSwitch 函数被触发.然后我将状态 serverSwitchValue 更改为与 x 相同的值.
预期:serverSwitchValue 和 x 在 console.log() 时应该具有相同的值.p>
实际:console.log()时,两个变量的值不同.
该程序似乎可以工作,但是在触发 console.log() 时,值不一样.为什么?
const [serverSwitchValue, setServerSwitchValue] = useState(false);const _toggleServerSwitch = x =>{设置服务器开关值(x);console.log('x 是:' + x);console.log('serverSwitchValue 是:' + serverSwitchValue);};
解决方案 setServerSwitchValue() 是一个异步函数,所以它并不意味着你会立即得到更新的值.你可以使用 useEffect
如下:
useEffect(() => {控制台.log(serverSwitchValue);}, [服务器开关值]);//仅在 open 更改时重新运行效果
希望对你有帮助.
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);
};
解决方案
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.
相关文章