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

如何修正React自定义useDeleteMessage Hook,使其仅在按钮点击时触发提示消息

Fix: Custom Hook Triggers on Page Load Instead of Button Click

Let's break down why your current code shows messages immediately on page refresh, and how to fix it:

Problem Root Cause

Right now, your useDeleteMessage hook is returning the result of calling openMessage the second your component renders, not a function that waits for user interaction. When you write <Button onClick={useDeleteMessage('loading' , 'loadedworking')}>, you’re executing the hook’s returned value (and triggering the messages) as soon as the card component mounts—not when the button is clicked.

Step-by-Step Fix

1. Update the useDeleteMessage Hook

Modify the hook to return the openMessage function itself (instead of running it right away) and clean up redundant parameter passing:

import React from 'react';
import { message } from 'antd';

const key = 'updatable';

export const useDeleteMessage = (loadingMsg, successMsg) => { 
  const openMessage = () => { 
    message.loading({ content: loadingMsg, key }); 
    setTimeout(() => { 
      message.success({ content: successMsg, key, duration: 2 }); 
    }, 1000); 
  }; 

  // Return the function reference, not its execution result
  return openMessage; 
};

We also removed the unused useState from the hook—no need to keep state that isn’t serving a purpose!

2. Adjust the card Component

Assign the hook’s returned function directly to the onClick prop (don’t call it immediately). This ensures the function only runs when the button is clicked:

import { Button } from 'antd';
import { useDeleteMessage } from './path-to-your-hook'; // Update this path to your hook file

const Card = () => {
  // Get the click handler function from the hook
  const handleDeleteMessage = useDeleteMessage('loading', 'loadedworking');

  return (
    <Button onClick={handleDeleteMessage}>按钮</Button>
  );
};

export default Card;

Why This Works

  • The hook now returns a reference to the openMessage function, not the result of running it.
  • When the button is clicked, React invokes this function, which triggers the loading message followed by the success message after a 1-second delay.
  • This follows React’s event handler pattern: onClick expects a function to execute when the event occurs, not the output of a function.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:12:44