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

React组件调用Django REST API报错:response.data.slice不是函数

React组件调用Django API报错排查与修复

问题代码

import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import '../styles/sales.css'; // Import the CSS file

function Sales() {
  const [propertyData, setPropertyData] = useState([]);

  useEffect(() => {
    // Fetch data from your Django API using Axios
    axios.get('http://127.0.0.1:8000/api/v1/core/for-sale/')
      .then((response) => {
        // Limit the photos to a maximum of four
        const limitedData = response.data.slice(0, 4);
        setPropertyData(limitedData);
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div className="sales-container">
      {propertyData.map((property) => (
        <div key={property.id} className="property-card">
          <Link to={`/property/${property.id}`}>
            <img src={property.main_photo} alt={property.title} className="property-image" />
            <h2 className="property-title">{property.title}</h2>
          </Link>
          <p className="property-description">{property.description}</p>
          <p className="property-details">
            {property.bedrooms} Bedrooms | ${property.price}
          </p>
        </div>
      ))}
    </div>
  );
}

export default Sales;

问题描述

已安装Axios库、配置CORS_ALLOWED_ORIGINS并添加corsheaders,但图片无法渲染,且控制台报错:

Error fetching data: TypeError: response.data.slice is not a function

问题原因与修复方案

1. 报错核心原因

slice()是JavaScript数组的专属方法,报错说明response.data不是数组。Django REST Framework默认开启分页后,API返回的是包含数组的对象,结构通常如下:

{
  "count": 10,
  "next": null,
  "previous": null,
  "results": [/* 房产数据数组 */]
}

直接对整个响应对象调用slice(),自然会触发类型错误。

2. 代码修复

修改Axios请求的处理逻辑,先提取results数组再做截取:

useEffect(() => {
  axios.get('http://127.0.0.1:8000/api/v1/core/for-sale/')
    .then((response) => {
      // 先取results数组,再限制数量为4条
      const limitedData = response.data.results.slice(0, 4);
      setPropertyData(limitedData);
    })
    .catch((error) => {
      console.error('Error fetching data:', error);
    });
}, []);

3. 图片无法渲染的补充排查

  • 检查property.main_photo的返回值:确保是完整可访问的URL(如http://127.0.0.1:8000/media/house1.jpg),如果是相对路径,需要拼接API域名(比如${API_BASE_URL}${property.main_photo})。
  • 验证Django媒体配置:确认settings.py中MEDIA_URL和MEDIA_ROOT设置正确,且开发环境中已在urls.py配置媒体文件访问路由:
# Django urls.py
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # 其他路由
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:25:13