小编典典

异步xmlhttp请求在反应

reactjs

我正在尝试在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加载并返回值后,我在更新时遇到问题。


阅读 278

收藏
2020-07-22

共1个答案

小编典典

使用组件的生命周期加载数据,然后异步设置状态。您还需要对返回的数据使用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>
2020-07-22