从Strapi v4获取数据在ReactJS中映射返回空数组的问题排查
Strapi数据映射返回空数组的问题修正
核心问题与修复步骤
1. URL拼写错误
请求URL缺少冒号:http//localhost:1337/api/recepts 应改为 http://localhost:1337/api/recepts,错误的URL会导致请求无法正常发送,进而返回空数据或错误。
2. Strapi响应结构处理错误
Strapi v4的API响应格式为外层包含data字段的对象,示例结构:
{ "data": [/* 业务数据数组 */], "meta": { /* 元数据信息 */ } }
你的useFetch直接将整个响应对象存入data,但组件中判断Array.isArray(data)会返回false(因为data是对象而非数组),导致渲染逻辑不执行。
修复:
在useFetch中提取响应里的data数组:
try { const res = await fetch(url); const json = await res.json(); setData(json.data); // 直接存储数组部分 setLoading(false); } catch (error) { setError(error); setLoading(false); }
3. 组件循环逻辑错误
你在map循环中错误使用了整个数组data而非循环变量el,同时key值和属性访问均存在错误:
key={data.id}应改为key={el.id}data.data.attributes.title应改为el.attributes.titledata.data.id应改为el.id
修复后的渲染代码:
return ( <div> {data?.map((el) => ( <div key={el.id} className="recept-card"> <h2>{el.attributes.title}</h2> <small>console list</small> <p>{el.attributes.body.substring(0, 200)}</p> <Link to={`/details/${el.id}`}>...</Link> </div> ))} </div> );
4. 错误状态的初始化与判断错误
useFetch中error初始化为数组[]不合理,应改为null(捕获的错误是对象类型,而非数组)- 组件中
error === []永远为false(数组是引用类型,不能用全等比较),应判断error是否存在
修复useFetch的error初始化:
const [error, setError] = useState(null);
修复组件的错误判断:
if (loading) { return <p>Loading...</p>; } else if (error) { return <p>Error: {error.message}</p>; }
5. 响应状态校验优化
可以在useFetch中增加HTTP响应状态校验,捕获404、500等错误:
try { const res = await fetch(url); if (!res.ok) { throw new Error(`请求失败:${res.status}`); } const json = await res.json(); setData(json.data); setLoading(false); } catch (error) { setError(error); setLoading(false); }
内容的提问来源于stack exchange,提问作者Viktor Helfrih
相关产品推荐
相关产品推荐

