React Native中useState Hook未即时更新,按钮需点击两次才生效问题
问题修复方案
根因说明
React 的useState状态更新是异步批量执行的,调用setOpenShop后,当前onShopPress函数作用域内的openShop仍然是本次点击触发时的旧值,不会立刻更新,因此后续判断逻辑始终基于旧值运行,才会出现需要点击两次的异常。
修复方案
方案一:基于目标更新值做判断
先计算要更新的openShop目标值,直接用该值做逻辑判断,不依赖旧状态:
const onShopPress = () => { const newOpenValue = !openShop; setOpenShop(newOpenValue); if (newOpenValue) { setTranslateY(-containerHeight); } else { setTranslateY(0); } console.log('shopping pressed'); };
方案二:移除冗余状态,使用派生值(更推荐)
translateY的取值完全可以由openShop和containerHeight直接计算得到,不需要单独声明为状态,可彻底避免状态不同步的问题:
const [openShop, setOpenShop] = useState(false); // 建议把containerHeight初始值改为0,避免后续数值运算出现非预期结果 const [containerHeight, setContainerHeight] = useState(0); // 直接计算translateY,无需单独维护state const translateY = openShop ? -containerHeight : 0; const onShopPress = () => { setOpenShop(!openShop); console.log('shopping pressed'); };
内容的提问来源于stack exchange,提问作者hellomello
相关产品推荐
相关产品推荐

