javascript - 在 create-react-app 创建的环境中获取本地 JSON 文件时出现 JSON 解析错误
问题描述
我正在学习 reactjs,并且正在使用create-react-app 创建的环境。我正在尝试从本地 json 文件中获取 json 数据,但是我收到了错误消息SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
在这个SO 答案中,我明白我需要添加一个协议,但是在添加它之后我得到了同样的错误。这是我正在尝试的组件
import React, { Component } from "react";
class Countries extends Component {
constructor(props) {
super(props);
this.state = {
countries: []
};
}
componentDidMount() {
fetch("http://localhost:3000/dataset.json")
.then(response => response.json())
.then(json => {
console.log(json);
})
.catch(error => console.error(error));
}
render() {
const countries = this.state.countries;
const rows = countries.map(country => (
<Country name={country.name} code={country.code} />
));
return (
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Code</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
</div>
);
}
}
function Country(props) {
return (
<tr>
<td>{props.name}</td>
<td>{props.code}</td>
</tr>
);
}
export default Countries;
感谢您的意见
解决方案
使用 Create React App 时,目录中的所有内容都public
将在站点的根目录中可用,因此您可以将dataset.json
文件移动到那里并直接获取/dataset.json
。
componentDidMount() {
fetch("/dataset.json")
.then(response => response.json())
.then(json => {
console.log(json);
})
.catch(error => console.error(error));
}
推荐阅读
- c - 尝试切换字符串中的字母时出现总线错误
- latex - 使用 Science.bst 模板文件,无法正确显示期刊文章的参考文献
- r - 将数据框中的列文本转换为一行内的多行
- r - 在 ggplot 上显示多行并带有分组(闪避)条
- javascript - 运行 JavaScript x 次,每次数组中的数字增加 1
- assembly - 这个 OR 与零 MIPS 指令有什么意义?
- javascript - 如何使底部标签栏仅出现在反应导航中嵌套堆栈的默认屏幕上?
- shopify - 跟踪自定义变体的库存
- swift - 在一个预期会在 swift 中返回“UITableViewCell”的函数中出现错误,如 Missing return
- python - 将列表转换为字典,其中每个键嵌套在下一个键下