为什么我在React Native中对此布尔值有两个不同的值? [英] Why do I have two different values on this boolean in React Native?

查看:141
本文介绍了为什么我在React Native中对此布尔值有两个不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在React Native App中,单击切换按钮后,函数 _toggleServerSwitch 被触发.然后,将状态 serverSwitchValue 更改为与 x 相同的值.

预期:当 console.log()时, serverSwitchValue x 的值应相同. >

实际:当console.log()时,两个变量具有不同的值.

该程序似乎可以运行,但是在触发 console.log()时,值并不相同.为什么?

const [serverSwitchValue, setServerSwitchValue] = useState(false);

  const _toggleServerSwitch = x => {
    setServerSwitchValue(x);
    console.log('x is: ' + x);
    console.log('serverSwitchValue is: ' + serverSwitchValue);
  };

解决方案

setServerSwitchValue()是一个异步函数,因此它并不意味着您可以立即获取更新的值.您可以使用useEffect如下:

useEffect(() => {
 console.log(serverSwitchValue);
}, [serverSwitchValue]); // Only re-run the effect if open changes

希望有帮助.

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中对此布尔值有两个不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆