Next.js读取本地JSON渲染列表报错:String类型无data属性
问题解决:从本地JSON获取Crate数据并展示失败
核心问题梳理
crates.map is not a function错误:因为你把字符串赋值给了数组类型的状态,字符串没有map方法Property 'data' does not exist on type String错误:你把解析后的JS对象转成了字符串,字符串不存在data属性- JSON文件格式不合法,TypeScript接口定义和实际数据类型不匹配
分步修复方案
1. 修正JSON文件格式
你的public/data.json外层缺少包裹大括号,正确格式如下:
{ "crates": [ { "id": 1, "nameCrate": "Pauls crate", "albums": ["Blue Bossa", "Boogarins"] }, { "id": 2, "nameCrate": "Lauras crate", "albums": ["ABBA", "Blof"] } ] }
2. 修正TypeScript接口定义
JSON中id是数字类型,albums是字符串数组,接口需与实际数据类型匹配:
interface Crate { id: number; nameCrate: string; albums: string[]; }
3. 修复fetch逻辑(关键)
res.json()已经把响应体解析成JavaScript对象,完全不需要JSON.stringify——这个方法会把JS对象转成JSON字符串,破坏数据结构。直接取对象内的crates数组赋值给状态即可:
useEffect(() => { fetch('data.json', { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }) .then((res) => res.json()) .then((resJson) => { setCrates(resJson.crates) }) }, [])
4. 优化渲染逻辑
初始状态已是空数组,无需额外判断crates &&;同时{...crates}是错误写法,单个项应对应crate:
<main> Main {crates.map((crate) => ( <div key={crate.id}>{crate.nameCrate}</div> ))} </main>
额外说明
- 不需要使用
params,读取本地静态JSON文件直接通过fetch访问文件路径即可 - 之前的
map方法错误,根源就是你把字符串赋值给了数组状态,导致无法调用数组方法
内容的提问来源于stack exchange,提问作者Paul Cudles
相关产品推荐
相关产品推荐

