Why do I have two different values on this boolean in React Native?(为什么我在 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.
这篇关于为什么我在 React Native 中的这个布尔值上有两个不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我在 React Native 中的这个布尔值上有两个不同的值?


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01