异步xmlhttp请求在反应

发布于 2021-01-31 22:44:15

我正在尝试在React中实现异步XMLHttpRequest。这是我的尝试:

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) {

      json_obj = xhr.responseText;

      status = true;

    } else {

      console.error(xhr.statusText);

    }

  }

};

xhr.onerror = function (e) {

  console.error(xhr.statusText);

};

xhr.send(null);



class Welcome extends React.Component {

  render() {

    return (

      <div>

          <img src= {status ?  json_obj[0].url : 'loading...'}></img>

      </div>

    );

  }

}

ReactDOM.render(

   <Welcome/>,

   document.getElementById('root')

);


<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

我一直在考虑添加侦听器,但我不知道该怎么做。

总的来说,异步XMLHttpRequest加载并返回值后,我在更新时遇到问题。

关注者
0
被浏览
69
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

    使用组件的生命周期加载数据,然后异步设置状态。您还需要对返回的数据使用JSON.parse。

    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 (
    
          <div>
    
              <img src= {this.state.json_obj ?  this.state.json_obj[0].url : 'loading...'}></img>
    
          </div>
    
        );
    
      }
    
    }
    
    ReactDOM.render(
    
       <Welcome/>,
    
       document.getElementById('root')
    
    );
    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    
    <div id="root"></div>
    


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看