在不安装本地服务器的情况下在 Reactjs 中加载本地 jSON 文件

load local jSON file in Reactjs without installing a localserver

我的结构是src/resource/file.json.

1.By 安装 load-json 并使用 require:

    class App extends Component{  

      constructor(props) {
            super(props);
            this.state = {summaryData: [], sortBy: null};
            this.sortContent = this.sortContent.bind(this);
            }
         componentWillMount() {

            require('../resource/file.json')
                  .then(response => {
                    // Convert to JSON
                    return response;
                  })
                  .then(findresponse => {
                    // findresponse is an object
                    console.log(findresponse);
                    this.setState({summaryData: findresponse});
                  })
                  .catch(norespone => {
                    console.log('Im sorry but i could not fetch anything');
                  });
              }

并出现消息: 找不到模块:无法解析 'C:\Xampp\htdocs\path\to\app\src\pages'

中的“../resource/file.json”
  1. 通过myJSON:

    request('https://api.myjson.com/bins/{id..}').then(sumres => {
      if (sumres) {
        this.setState({summaryData: sumres});
        console.log(this.state.summaryData);
      }
    });
    

    }

但控制台或网络选项卡中没有显示任何内容。有人可以提出解决方案吗? 是否可以在不安装本地服务器的情况下加载 json 文件?

是的!可以将 JSON 加载到您的页面中。在导入模块的脚本顶部,导入 json 文件。

示例:

import React from 'react';
import jsonData from '../resource/file.json';
etc...

对于您的情况,如果您尝试将其设置为状态,只需在组件初始化时设置状态即可。

constructor(props) {
    super(props);
    this.state = {
        summaryData: jsonData.myArray, 
        sortBy: null
    };

    this.sortContent = this.sortContent.bind(this);
}

希望对您有所帮助!