loading json data from local file into React JS

前端 未结 8 1773
无人及你
无人及你 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:43

    You are opening an asynchronous connection, yet you have written your code as if it was synchronous. The reqListener callback function will not execute synchronously with your code (that is, before React.createClass), but only after your entire snippet has run, and the response has been received from your remote location.

    Unless you are on a zero-latency quantum-entanglement connection, this is well after all your statements have run. For example, to log the received data, you would:

    function reqListener(e) {
        data = JSON.parse(this.responseText);
        console.log(data);
    }
    

    I'm not seeing the use of data in the React component, so I can only suggest this theoretically: why not update your component in the callback?

提交回复
热议问题