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 中的这个布尔值上有两个不同的值?


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01