React对接Drupal JSON API时posts.map is not a function错误解决
解决React中Drupal JSON API返回对象导致的map函数报错问题
Drupal的JSON API模块返回的数据遵循标准结构,所有资源数组都被包裹在外层对象的data字段中,你直接将整个返回对象赋值给posts状态,导致posts是对象而非数组,因此调用map时会抛出TypeError: posts.map is not a function错误。
解决方案
修改useEffect中的数据处理逻辑,提取返回对象里的data数组作为posts的状态值,同时添加兜底处理避免异常:
import React, { useEffect, useState } from "react"; import Slider from "react-slick"; function Homeslidersection() { const settings = { dots: false, arrows: false, infinite: true, speed: 500, autoplay: false, slidesToShow: 1, slidesToScroll: 1, }; const [posts, setPosts] = useState([]); useEffect(() => { async function loadPosts() { const response = await fetch( "http://localhost/drupalreact/jsonapi/node/banner?include=field_banner_image" ); if (!response.ok) { return; } const responseData = await response.json(); // 提取data数组,若data不存在则赋值空数组兜底 setPosts(responseData.data || []); } loadPosts(); }, []); return ( <> <div className="home-slider-section"> <div className="homesliderwrapper"> <div className="home-slider-folder"> <Slider {...settings}> {posts.map((post, index) => ( <div key={index} className="home-slider-blog-box-section"> <div className="home-slider-image"> {/* 从Drupal返回的结构中提取图片URL */} <img src={post.relationships.field_banner_image.data?.attributes.uri.url} alt={post.attributes.title} /> </div> <div className="home-slider-text-folder1"> <h2>{post.attributes.title}</h2> <span>{post.attributes.field_subtitle}</span> <p>{post.attributes.body.value}</p> <a href={`/banner/${post.id}`} className="Read-More"> Read More </a> </div> </div> ))} </Slider> </div> </div> </div> </> ); } export default Homeslidersection;
关键说明
- 提取数据数组:Drupal JSON API返回的资源列表始终在
data字段中,必须通过responseData.data获取实际的数组数据 - 兜底处理:添加
|| []确保即使接口返回的data为undefined或null,posts依然是一个空数组,避免map报错 - 渲染真实数据:补充了从Drupal返回结构中提取标题、副标题、图片等真实数据的示例,替换静态文本以正确展示接口返回内容
内容的提问来源于stack exchange,提问作者Omkar Dhumal
相关产品推荐
相关产品推荐

