[英]Access JSON file in React without importing it
I have been importing data in the form of a JSON
file into a React component: 我一直在以
JSON
文件的形式将数据导入React组件:
import data from '../../public/json/data.json';
I am using the create-react-app tool, and when I run npm run build
, as expected the data.json
file is bundled as part of the build/static/main.js
file. 我正在使用create-react-app工具,当我运行
npm run build
,正如预期的那样, data.json
文件被捆绑为build/static/main.js
文件的一部分。
What I would like is for this data.json
file not to be bundled but to be referenced at run-time each time the component runs. 我想要的是这个
data.json
文件不是捆绑的,而是在每次运行组件时在运行时引用。 Ie so that it can be edited in the built app and for these edits to show in the app. 即,它可以在构建的应用程序中进行编辑,并在应用程序中显示这些编辑。 I thought that by including it in my
public
(as opposed to src
) folder this would work, but of course I am still importing
it so it is bundled. 我认为通过将它包含在我的
public
(而不是src
)文件夹中,这可以工作,但当然我仍在importing
它,因此它被捆绑。 Is there a way to reference it without bundling it? 有没有办法在没有捆绑的情况下引用它?
Use the fetch API to retrieve the JSON file asynchronously. 使用fetch API异步检索JSON文件。
Check out https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch for example implementations. 有关示例实现,请查看https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.