【发布时间】:2021-12-03 01:03:34
【问题描述】:
美好的一天,
我正在尝试从位于我的 react 应用程序的公共文件夹中的本地 JSON 文件中获取数据。我知道这是 SO 中的一个常见问题,并且我已经事先查找了与我的问题相关的主题,但下面是最近的一个。
Fetch local JSON file from public folder ReactJS
我正在使用下面的代码来获取我的 json 文件:
const getResponse = () => {
fetch('responseScript.json')
.then(response => { response.json() })
.then(data => { console.log(data) })
}
useEffect(() => {
getResponse();
})
主要问题是每当我从 json 文件中获取数据时,都会出现未定义和错误:
responseScript 位于公用文件夹中。我还检查了 devtools,在网络选项卡中,我可以看到请求状态代码是 200 OK。
我不确定它是否会增加问题,但我正在使用打字稿。我也研究过使用 FileStructure,但这似乎对我也不起作用。
编辑
我的 JSON 结构如下所示:
[
{
"Category":"Some text here",
"Issue":"Some text here",
"Answer":"Some text here",
"Response":"Some text here"
},
{
"Category":"Some text here",
"Issue":"Some text here",
"Answer":"Some text here",
"Response":"Some text here"
},
{
"Category":"Some text here",
"Issue":"Some text here",
"Answer":"Some text here",
"Response":"Some text here"
}
]
文件夹结构是
感谢任何帮助。谢谢!
【问题讨论】:
-
似乎错误指向错误的 json,检查它实际返回的内容
-
相对于 json 文件的位置,您的目录结构是什么样的?
-
这表明您的“JSON”实际上是 HTML。
-
应该是
fetch(myRequest).then(response => response.json())你没有返回response.json -
附上项目的文件夹结构图。
标签: reactjs json typescript fetch-api