loading json data from local file into React JS

前端 未结 8 1718
无人及你
无人及你 2020-11-30 00:33

I have a React component and I want to load in my JSON data from a file. The console log currently doesn\'t work, even though I\'m creating the variable data

8条回答
  •  粉色の甜心
    2020-11-30 00:51

    If you want to load the file, as part of your app functionality, then the best approach would be to include and reference to that file.

    Another approach is to ask for the file, and load it during runtime. This can be done with the FileAPI. There is also another StackOverflow answer about using it: How to open a local disk file with Javascript?

    I will include a slightly modified version for using it in React:

    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          data: null
        };
        this.handleFileSelect = this.handleFileSelect.bind(this);
      }
    
      displayData(content) {
        this.setState({data: content});
      }
    
      handleFileSelect(evt) {
        let files = evt.target.files;
        if (!files.length) {
          alert('No file select');
          return;
        }
        let file = files[0];
        let that = this;
        let reader = new FileReader();
        reader.onload = function(e) {
          that.displayData(e.target.result);
        };
        reader.readAsText(file);
      }
    
      render() {
        const data = this.state.data;
        return (
          
    { data &&

    {data}

    }
    ); } }

提交回复
热议问题