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

React.js:将控制器返回数据渲染为卡片求助

Solution to Render Cards from API Data in React.js

Hey there! I’ll help you get those cards rendering properly with the data from your API. Let’s break this down step by step.

First, I can see your componentDidMount is already fetching data and updating the person state—great start! Now we just need to map over that state array in the render method to generate the same card structure as your example.

Here’s the updated code with the completed render method:

class UserList extends React.Component {
  constructor() {
    super();
    this.state = { person: [], isLoading: true }; // Added loading state for better UX
  }

  componentDidMount() {
    this.UserList();
  }

  UserList() {
    fetch("/ReactJS/GetMessage")
      .then(res => {
        if (!res.ok) {
          throw new Error("Network response was not ok"); // Handle HTTP errors
        }
        return res.json();
      })
      .then(result => {
        this.setState({
          person: result,
          isLoading: false // Turn off loading once data is fetched
        });
      })
      .catch(error => {
        console.error("There was a problem fetching the data:", error);
        this.setState({ isLoading: false }); // Handle error state
      });
  }

  render() {
    const { person, isLoading } = this.state;

    // Show loading message while data is being fetched
    if (isLoading) {
      return <div>Loading users...</div>;
    }

    // If no data is returned, show empty state
    if (person.length === 0) {
      return <div>No users found.</div>;
    }

    // Map over the person array to render each card
    return (
      <div className="card-container"> {/* Match the container class from your example */}
        {person.map((user, index) => (
          <div key={user.id || index} className="card"> {/* Use unique key, prefer user.id if available */}
            <img src={user.avatar} alt={`${user.name}'s avatar`} className="card-avatar" />
            <div className="card-content">
              <h3 className="card-name">{user.name}</h3>
              <p className="card-title">{user.title}</p>
              <p className="card-bio">{user.bio}</p>
            </div>
          </div>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<UserList />, document.getElementById('form'));

Key Notes:

  • Loading State: Added isLoading to give feedback to users while data loads—this improves UX instead of showing a blank screen.
  • Error Handling: Added a catch block to handle fetch failures, so you can debug issues if the API call fails.
  • Unique Keys: When mapping over arrays in React, always include a unique key prop. I used user.id (assuming your API returns an ID for each user) or fallback to index if IDs aren’t available.
  • Card Structure: The JSX inside the map matches the typical card structure from your example—adjust the class names (card-container, card, etc.) and data properties (user.name, user.avatar, etc.) to exactly match what your API returns and the styles in your original example.

Quick Checks:

  1. Make sure your API returns data in an array format where each object has the properties you’re using (like name, avatar, title). If your API uses different property names (e.g., fullName instead of name), update the JSX to match.
  2. Ensure your CSS styles (from the example) are included in your project so the cards look correct.

That should get your cards rendering just like the example with real API data! 😊

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:19:36