首页 > 解决方案 > 在 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;

感谢您的意见

标签: javascriptreactjs

解决方案


使用 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));
}

推荐阅读