You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让React useEffect仅在两个状态同时变化时触发?

解决方法

问题核心是:searchTerms 更新后,data?.hits.total.value 会异步加载更新,导致两次触发 useEffect。要实现仅当两者同时变化时执行逻辑,需要手动追踪两个值的上一次状态,判断是否同时发生变更。

实现步骤:

  1. 使用 useRef 存储上一次的 searchTerms 和 total.value 状态
  2. 在 useEffect 中对比当前值与上一次值,仅当两者都发生变化时执行目标函数
  3. 执行逻辑后更新 ref 的状态,用于下次对比

代码示例:

import { useEffect, useRef } from 'react';

// ... 其他业务代码

const prevStateRef = useRef({
  searchTerms: '',
  totalValue: null
});

useEffect(() => {
  const currentTotalValue = data?.hits.total.value;
  const currentSearchTerms = searchTerms;

  // 判断两个值是否都和上一次状态不同
  const hasBothChanged = 
    currentSearchTerms !== prevStateRef.current.searchTerms && 
    currentTotalValue !== prevStateRef.current.totalValue;

  if (hasBothChanged && currentSearchTerms) {
    analyticsService?.logEvent(ANALYTICS_EVENTS.SEARCH_COMPLETED, {      
      total_results: currentTotalValue,
      error_message: null,
    });
  }

  // 更新上一次状态,确保下次对比准确
  prevStateRef.current = {
    searchTerms: currentSearchTerms,
    totalValue: currentTotalValue
  };
}, [searchTerms, data?.hits.total.value]);

逻辑说明:

  • 每次 searchTerms 或 total.value 变更时,useEffect 都会触发,但只有当两者同时和上一次状态不同时,才会执行日志上报。
  • 首次加载时,如果 searchTerms 和 total.value 都有有效初始值,会触发一次(符合首次搜索的场景);后续只有当用户输入新的 searchTerms 且对应的新 total.value 返回时,才会触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:25:54