Asynchronous xmlhttp request in react

后端 未结 4 1315
感动是毒
感动是毒 2021-02-10 05:16

I am trying to implement asynchronous XMLHttpRequest in react. Here is my attempt:

4条回答
  •  误落风尘
    2021-02-10 05:40

    Use the component's lifecycle to load the data and then set the state asynchronously. You will also need to use JSON.parse on the data returned to you.

    class Welcome extends React.Component {
      state = {}
    
      componentDidMount() {
        var xhr = new XMLHttpRequest();
        var json_obj, status = false;
        xhr.open("GET", "https://jsonplaceholder.typicode.com/photos/", true);
        xhr.onload = function (e) {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              var json_obj = JSON.parse(xhr.responseText);
              status = true;
              this.setState({ json_obj });
            } else {
              console.error(xhr.statusText);
            }
          }
        }.bind(this);
        xhr.onerror = function (e) {
          console.error(xhr.statusText);
        };
        xhr.send(null);
      }
    
      render() {
        return (
          
    ); } } ReactDOM.render( , document.getElementById('root') );
    
    
    

提交回复
热议问题