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

如何仅修改被点击按钮的加载状态,避免同条件下其他按钮同步加载?

问题核心

你现在的两个按钮绑定了同一个isLoading状态,只要这个状态变为true,所有绑定它的组件都会触发加载效果,这就是两个按钮同步变加载的原因。

解决方案

给你两种可直接落地的实现方式:

方案1:修改自定义Hook(优先推荐)

如果useRespondConsent是你项目内自行封装的Hook,直接调整它的返回值,区分不同操作的加载状态:

// 调整后的useRespondConsent Hook
const useRespondConsent = () => {
  const [isSendLoading, setIsSendLoading] = useState(false)
  const [isNotSendLoading, setIsNotSendLoading] = useState(false)

  const handleRespond = async (isSend) => {
    if (isSend) {
      setIsSendLoading(true)
    } else {
      setIsNotSendLoading(true)
    }
    try {
      // 保留原有接口请求逻辑
      await request(xxx)
    } finally {
      if (isSend) {
        setIsSendLoading(false)
      } else {
        setIsNotSendLoading(false)
      }
    }
  }

  return {
    isSendLoading,
    isNotSendLoading,
    handleRespond
  }
}

// 组件内使用
const { isSendLoading, isNotSendLoading, handleRespond } = useRespondConsent();

<ButtonPrimary isLoading={isSendLoading} onClick={() => handleRespond(true)}>
   Send
</ButtonPrimary>

<Button isLoading={isNotSendLoading} onClick={() => handleRespond(false)}>
   Not send
</Button>

方案2:组件内新增状态兼容(无需修改原有Hook)

如果没法改动useRespondConsent的逻辑,可以在组件内新增状态标记当前点击的按钮,结合原有的isLoading判断加载状态:

const { isLoading, handleRespond } = useRespondConsent();
// 新增状态记录点击的操作类型,true对应Send,false对应Not send,null代表无进行中的操作
const [activeOperate, setActiveOperate] = useState(null);

const wrapHandleRespond = async (isSend) => {
  setActiveOperate(isSend)
  try {
    await handleRespond(isSend)
  } finally {
    setActiveOperate(null)
  }
}

<ButtonPrimary 
  isLoading={isLoading && activeOperate === true} 
  onClick={() => wrapHandleRespond(true)}
>
   Send
</ButtonPrimary>

<Button 
  isLoading={isLoading && activeOperate === false} 
  onClick={() => wrapHandleRespond(false)}
>
   Not send
</Button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:24:04