代码之家  ›  专栏  ›  技术社区  ›  Mario

在create react app创建的环境中获取本地JSON文件时出现JSON解析错误

  •  1
  • Mario  · 技术社区  · 6 年前

    我在学习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;
    

    谢谢你的评论

    1 回复  |  直到 6 年前
        1
  •  2
  •   Tholle    6 年前

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