You need to enable JavaScript to run this app. React useState切换布尔值异常,状态为false时if判断仍通过如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

React useState切换布尔值异常,状态为false时if判断仍通过如何解决?

问题原因

你遇到的是典型的React闭包陷阱:通过jQuery的$body.on绑定的点击事件回调,在绑定时捕获了当时的isEraser状态值,后续组件重渲染更新isEraser时,旧的事件回调没有被更新,依然保留了首次绑定时的状态引用,所以判断逻辑会出现不符合预期的情况。

解决方案

方案1:用useEffect动态绑定解绑事件

每次isEraser变化时,销毁旧的事件回调,绑定包含最新状态的新回调:

useEffect(() => {
  const handleAnnotateClick = function(e) {
    console.log('Eraser is set to', isEraser);
    if (isEraser === true) {
        setIsAlert(1);
        this.style.backgroundColor = '';
        this.classList.remove('tvs-annotated-text');
        this.classList.remove('tvs-annotate-element');
    }
  }
  $body.on('click', '.tvs-annotated-text, .tvs-annotate-element', handleAnnotateClick)
  // 清理函数:组件卸载/依赖变化时解绑旧事件
  return () => {
    $body.off('click', '.tvs-annotated-text, .tvs-annotate-element', handleAnnotateClick)
  }
}, [isEraser, setIsAlert]) // 所有回调内用到的状态、方法都要放进依赖数组

方案2:用useRef存储最新状态值

useRef返回的是可变引用,不会被闭包捕获固定值,可以直接读取最新的状态:

const [ isEraser, setIsEraser ] = useState(false);
// 新建ref同步isEraser的最新值
const isEraserRef = useRef(isEraser);
useEffect(() => {
  isEraserRef.current = isEraser;
}, [isEraser])

// 事件回调内读取ref的current属性判断
$body.on('click', '.tvs-annotated-text, .tvs-annotate-element', function(e) {
  console.log('Eraser is set to', isEraserRef.current);
  if (isEraserRef.current === true) {
    setIsAlert(1);
    this.style.backgroundColor = '';
    this.classList.remove('tvs-annotated-text');
    this.classList.remove('tvs-annotate-element');
  }
});

方案3:替换为React原生事件绑定

直接在.tvs-annotated-text、.tvs-annotate-element元素上用React的onClick绑定事件,不需要额外处理就能拿到最新的状态值,从根源避免闭包问题。

内容的提问来源于stack exchange,提问作者Michal Gally

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 00:36:14