如何修正React自定义useDeleteMessage Hook,使其仅在按钮点击时触发提示消息
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
openMessagefunction, 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:
onClickexpects a function to execute when the event occurs, not the output of a function.
内容的提问来源于stack exchange,提问作者anup

