React中无法console.log JSON数据,axios未发请求,求改getAllUser等方法
Fixing Your Axios Request & User Display Issues in React Class Component
Hey there! Let's break down why your API request isn't going out and get those user names/emails showing up properly. From what you described, the main issues are likely that your getAllUser() method isn't being triggered, and the data flow between your fetch and display methods isn't set up correctly. Here's how to fix it:
Key Issues to Address
- Your
getAllUser()method probably isn't being called anywhere (so the request never fires) - You're not storing the fetched data in your component's state, so
displayUsers()has no data to render - Unnecessary import of
postfrom axios (you don't need it for a GET request)
Modified Complete Code
import React, { Component } from 'react'; import axios from 'axios'; // No need to import post unless you use it class UserList extends Component { // Initialize state to hold user data and loading/error states state = { users: [], isLoading: true, error: null }; // Trigger data fetch when component finishes mounting componentDidMount() { this.getAllUser(); } // Updated getAllUser with proper axios handling and state management getAllUser = async () => { try { // Replace YOUR_API_ENDPOINT with your actual API URL const response = await axios.get('YOUR_API_ENDPOINT'); // Store fetched users in component state this.setState({ users: response.data, isLoading: false }); // Log response to verify data console.log('Fetched users:', response.data); } catch (error) { this.setState({ error: error.message, isLoading: false }); console.error('Error fetching users:', error); } }; // Updated displayUsers to render data from state displayUsers = () => { const { users, isLoading, error } = this.state; // Show loading message while data is being fetched if (isLoading) return <div>Loading users...</div>; // Show error message if request fails if (error) return <div>Error: {error}</div>; // Render user list if data is available return users.map(user => ( <div key={user.id} className="user-card"> <p><strong>User Name:</strong> {user.userName}</p> <p><strong>Email:</strong> {user.email}</p> <hr /> </div> )); }; render() { return ( <div className="user-container"> <h2>Registered Users</h2> {/* Render the user list by calling displayUsers */} {this.displayUsers()} </div> ); } } export default UserList;
What Changed & Why
- Added Component State: We initialized state to track users, loading status, and errors. This lets us manage the full data lifecycle and give feedback to users.
- Called
getAllUser()incomponentDidMount: This lifecycle hook runs right after the component mounts, ensuring our API request fires automatically when the component loads. - Refactored
getAllUser(): We usedasync/awaitfor cleaner async code, removed the unnecessarypostimport, and stored the fetched data in state. Error handling ensures we catch and display any request issues. - Improved
displayUsers(): Now it first checks for loading/error states, then maps over the stored users to render their details. We added akeyprop (required for React lists) to avoid warnings.
Quick Post-Fix Checks
- Double-check your API endpoint URL is valid and reachable
- Confirm the API response actually includes
userNameandemailfields (adjust the code if field names differ, likeusernameinstead ofuserName) - If you hit CORS errors once the request fires, you'll need to handle that on the API side or set up a proxy in your React app
内容的提问来源于stack exchange,提问作者stone rock
相关产品推荐
相关产品推荐

