【问题标题】:JSON parse error when fetching a local JSON file in an enviroment created by create-react-app在 create-react-app 创建的环境中获取本地 JSON 文件时出现 JSON 解析错误
【发布时间】:2019-08-08 05:30:27
【问题描述】:

我正在学习 reactjs,我正在玩 create-react-app 创建的环境。我正在尝试从本地 json 文件中获取 json 数据,但我收到了错误消息 SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data" 在这个 SO answer 我明白我需要添加一个协议,但是在添加它之后我得到了同样的错误。这是我正在尝试的组件

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;

感谢您的cmets

【问题讨论】:

  • 尝试将dataset.json 直接添加到您的public 中,然后改写fetch("/dataset.json")。或者您可以利用 Webpack 并仅导入 JSON 文件并将其制成一个对象。 import dataset from "./path/to/dataset.json"
  • 是的,它是一个有效的 json,我认为这很可能,因此我尝试了一个只有 javascript 的代码并且数据加载正确
  • 感谢 Tholle,将数据集文件移动到公共目录并将获取 url 更改为 /dataset.json 完成了这项工作。您能否开发您提到的第二种方法
  • @user615274 Create React App 在后台使用 Webpack,它不仅允许您导入 JavaScript 文件,例如import MyComponent from './MyComponent.js',还有 JSON 文件。尝试将dataset.json移动到与Countries组件文件相同的目录并写入import dataset from './dataset.json',您将在dataset变量中自动将数据作为对象直接在文件中。

标签: javascript reactjs


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 2014-09-17
    • 2021-06-08
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    相关资源
    最近更新 更多