在react项目中,无法读取SimpleSample.json文件,一直找不到怎么解决?

Parent01.js

import React, { Component } from 'react';
import $ from 'jquery';

import constantData from './data/SimpleSample.json';

class Parent01 extends Component {
    constructor(props) {
        super(props)

    }

    Ad = () => {
        alert('cac');
        /*
        console.log("constantData  taype is ="+typeof(constantData));
        console.log("employees  taype is ="+typeof(constantData.employees));
        console.log("employees  length = "+constantData.employees.length);
        console.log("No.1 givenName ="+constantData.employees[0].giveName);
        console.log("No.1 FamilyName ="+constantData.employees[0].giveName);
        console.log("No.1 Salary"+constantData.employees[0].salary);
        console.log("type of No.1 Salary"+typeof(constantData.employees[0].salary));
        */

        var test;
        if(window.XMLHttpRequest){
            test = new XMLHttpRequest();
        }else if(window.ActiveXObject){
            test = new window.ActiveXObject();
        }else{
            alert("请升级至最新版本的浏览器");
        }
        if(test !=null){
            test.open("GET","./data/SimpleSample.json",true);
            test.send(null);
            test.onreadystatechange=function(){
                if(test.readyState==4&&test.status==200){
                    var obj = JSON.parse(test.responseText);
                    alert(obj);
                }
            };

        }
    }

    render() {
        return (
            <div>
                <table>
                    <tbody>
                        <tr data-resourceuuid="201612121641078700726">
                            <td width="30%">2</td>
                            <td width="35%">3</td>
                            <td width="30%"><a href="#" onClick={this.Ad}>点击</a></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        )
    }
}


export default Parent01;

data文件下的SimpleSample.json文件

{
  "employees": [
    {
      "FamilyName": "张",
      "giveName": "三",
      "salary": 1
    },
    {
      "FamilyName": "李",
      "giveName": "四",
      "salary": 2
    },
    {
      "FamilyName": "王",
      "giveName": "二",
      "salary": 3
    }
  ]
}

图片描述

阅读 2.8k
2 个回答

json扩展名有loader吗?

webpack 里给 json 文件配个 loader,或者改SimpleSample.jsonSimpleSample.js, 内容为:

export default {
    ... your json
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题