React无npm依赖:函数式实现请求触发1秒自动消失通知方案
Hey there! Let's get your React notification feature working smoothly. I'll walk through the fixes and improvements step by step, sticking strictly to functional components and no extra npm dependencies (we'll keep axios since you're already using it—though if you wanted to ditch it entirely, we could swap in the native fetch API instead!).
Step 1: Fix State Management in the Index Component
The main issue with your original code is that you're trying to render the Notification component directly inside the axios callback, which won't add it to the DOM. Instead, we'll use React's useState hook to track whether the notification should be visible and what text it should display.
Here's the updated Index.js:
import React, { useState } from 'react'; const axios = require('axios'); import Notification from '../notifications/Notification'; // Double-check this import path matches your folder structure const Index = () => { // State to control notification visibility and content const [notification, setNotification] = useState({ show: false, text: '' }); const getData = () => { axios.get('your-actual-api-url') // Replace with your real API endpoint .then(response => { // Show success notification setNotification({ show: true, text: response.data }); // Auto-hide after 1 second setTimeout(() => { setNotification(prevState => ({ ...prevState, show: false })); }, 1000); }) .catch(error => { console.error('Failed to fetch data:', error); // Optional: Show error notification setNotification({ show: true, text: 'Oops! Failed to load data.' }); setTimeout(() => { setNotification(prevState => ({ ...prevState, show: false })); }, 1000); }); }; return ( <div> <button onClick={getData}>Get data</button> {/* Only render the notification when `show` is true */} {notification.show && <Notification text={notification.text} />} </div> ); }; export default Index;
Step 2: Fix the Notification Component
Your original Notification component had a small bug with rendering props, plus we'll add some basic styling to make it look like a proper toast notification:
Updated Notification.js:
import React from 'react'; const Notification = (props) => { return ( <div style={{ position: 'fixed', top: '20px', right: '20px', padding: '15px 25px', backgroundColor: '#4CAF50', // Green for success color: 'white', borderRadius: '4px', boxShadow: '0 2px 6px rgba(0, 0, 0, 0.2)', zIndex: 1000 }}> <p>{props.text}</p> {/* Fixed: Use curly braces to access the prop value */} </div> ); }; export default Notification;
Step 3: Simplify the App Component
You don't need to pass the Notification component as a prop to Index—Index can just import it directly. Here's the cleaned-up App.js:
import React from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import Index from './components/index/index'; const App = () => { return ( <BrowserRouter> <Route exact path="/" component={Index} /> </BrowserRouter> ); }; export default App;
Quick Breakdown of Key Changes
- State Management: We use
useStateto track the notification's visibility and content—this is the standard way to handle state in functional React components. - Conditional Rendering: The notification only appears when
notification.showistrue, so it stays hidden until the API call completes. - Auto-Hide Logic:
setTimeout(a built-in browser function) toggles theshowstate back tofalseafter 1 second—no extra dependencies needed. - Prop Fix: We added curly braces around
props.textto render the actual value instead of the string "props.text".
内容的提问来源于stack exchange,提问作者TilikWebDeloper

