javascript - 使用 React 从 JSON 文件中读取数据
问题描述
我对使用 react 很陌生,我使用 IntelliJ 作为我的 IDE。
我试图在我的网站上显示 JSON 数据文件的内容,但我收到错误消息,说我创建了非法的导入减速。
import PostData from "./JSONData.js";
我的班级在班级中加载信息如下
class Invoice extends React.Component
{
render()
{
return (
<div className ="container">
<h2>Allstate NI Graduate Application</h2>
<h2>Invoice</h2>
{PostData.map((postDetail, index)=>{
return <h1>{postDetail.code}</h1>
})}
</div>
);
}
}
这是我的主要 HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gerry Byrne and David Wilson - ReactJS Tutorials</title>
<img src="../Drawable/carImage.png" id="carImg">
<!--Bootstap CSS-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"
integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4"
crossorigin="anonymous">
<!-- Tells the file to get the react.js file from a CDN.-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.0/react.js"></script>
<!--Tells the file to get the react-dom.js file from a CDN-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.0/react-dom.js"></script>
<!--The above two scripts used to be one but have since been seperated / ReactDom is only used to render ReactDOM.render()-->
<!---->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
<!--Tells the file to get the compiler file from a CDN-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
<!---->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/2.5.2/ReactRouter.min.js"></script>
<link rel="stylesheet" href="../css/style.css" />
<!-- Latest compiled and minified CSS Bootstrap-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"></link>
</head>
<body>
<div id="contentgoeshere"></div>
<br/>
<script type="text/jsx" src = "../JavaScript/ReactJSV3.js"></script>
</body>
</html>
我不确定我需要添加什么才能让我的项目导入这些文件。这是我得到的错误:
解决方案
它非常简单。您可以简单地导入.json
文件
import myJson from '../assets/my_json.json';
并myJson
直接使用
my_json.json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
}
}
]
}
或者
您可以导出对象(如果想使用 .js 文件)并导入另一个模块。
const myJson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
}
}
]
}
export default myJson;
进口声明
import myJson from '../assets/my_json.js';
推荐阅读
- java - RetryTemplate 只执行一次
- reactjs - React 组件总是恢复到数组中的最后一项
- selenium-webdriver - Selenium-在 div 弹出窗口中向下滚动
- html - 如何在css中创建两个形状的联合并将阴影应用于最终形状?
- x86-16 - 使用代码段和指令指针生成指令的地址
- javascript - React - useState 钩子访问状态
- c - 如何读取 IIS 模块中的请求发布文件?
- spring-boot - 将 Spring Boot 1.5.10 升级到 2.1.11
- git - 如何将重复的存储库作为来自其他组织的原始存储库的分支
- python-3.x - 当我点击运行按钮时消息是 TypeError: Student() 没有参数