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

在React模板中调用API获取Django后端数据的实现疑问

Hey there! Let's get your Django backend data showing up in your Hero.js component step by step. Since you're new to working with APIs in React, I'll break this down super clearly so you can follow along.

Step 1: Verify Your Django API is Working First

Before writing any React code, confirm your Django API is returning the data you need. Open your browser or a tool like Postman and visit your API endpoint (e.g., http://localhost:8000/api/your-model-name/). You should see JSON that looks like this:

[
  {
    "id": 1,
    "title": "Your First Title",
    "objective": "Your first objective text"
  },
  {
    "id": 2,
    "title": "Your Second Title",
    "objective": "Your second objective text"
  }
]

If you don't see this, double-check your Django model, serializer, and API routing first—React can't fetch data that isn't being served correctly!

Step 2: Add Data Fetching Logic to Hero.js

We'll use React's built-in useState (to store data/loading states) and useEffect (to run the API request when the component loads). Here's how to update your Hero.js:

import React, { useState, useEffect } from 'react';

const Hero = () => {
  // Set up state to hold our data, loading status, and errors
  const [modelItems, setModelItems] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  // Fetch data when the component mounts
  useEffect(() => {
    const fetchModelData = async () => {
      try {
        // Replace this URL with your actual Django API endpoint!
        const response = await fetch('http://localhost:8000/api/your-model-name/');
        
        // Check if the request succeeded
        if (!response.ok) {
          throw new Error(`Failed to fetch data: ${response.status}`);
        }

        const data = await response.json();
        setModelItems(data);
        setIsLoading(false); // Turn off loading once data is fetched
      } catch (err) {
        setError(err.message);
        setIsLoading(false);
      }
    };

    fetchModelData();
  }, []); // Empty dependency array = run only once when component mounts

  // Handle loading state
  if (isLoading) {
    return <div>Loading your data...</div>;
  }

  // Handle error state
  if (error) {
    return <div>Oops! Error loading data: {error}</div>;
  }

  // Render the data once it's loaded
  return (
    <div className="hero-component">
      <h1>My Model Data</h1>
      {modelItems.map(item => (
        <div key={item.id} className="model-item">
          <h2>*{item.title}*</h2>
          <p>{item.objective}</p>
        </div>
      ))}
    </div>
  );
};

export default Hero;

A few key notes here:

  • Replace http://localhost:8000/api/your-model-name/ with your actual API path
  • We use map() to loop through the array of items from Django—each item needs a unique key (we use the id field since it's unique)
  • We handle loading and error states to give users feedback instead of just a blank page
Step 3: Fix CORS Issues (If You Run Into Them)

If you see an error about "CORS policy" in your browser console, that's because React (usually running on localhost:3000) is trying to access Django (usually localhost:8000) which is a different domain. To fix this:

  1. Install the Django CORS package:
pip install django-cors-headers
  1. Update your Django settings.py:
# Add corsheaders to INSTALLED_APPS
INSTALLED_APPS = [
    # ... your other apps
    'corsheaders',
]

# Add CorsMiddleware to MIDDLEWARE (put it near the top!)
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    # ... your other middleware
]

# Allow all origins (safe for development only—lock this down in production!)
CORS_ALLOW_ALL_ORIGINS = True

Restart your Django server after making these changes.

Step 4: Double-Check Your App.js Routing

Make sure your Hero component is set as the home route in App.js (assuming you're using react-router-dom):

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Hero from './Hero'; // Adjust the import path if needed

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Hero />} />
        {/* Add other routes here if you have them */}
      </Routes>
    </Router>
  );
}

export default App;
Quick Check: Make Sure Your Django Serializer Includes the Right Fields

If your API isn't returning title or objective, confirm your Django serializer includes those fields:

from rest_framework import serializers
from .models import YourModelName

class YourModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = YourModelName
        fields = ['id', 'title', 'objective'] # Make sure these fields are listed!

That's it! Once you've made these changes, your Hero component should display the data from your Django model. If you run into specific errors, feel free to share the console logs or more details about your setup.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:07:33