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 中的这个布尔值上有两个不同的值?
基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
