Asynchronous xmlhttp request in react

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

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

4条回答
  •  余生分开走
    2021-02-10 05:42

    You need to perform the ajax request within the React lifecycle. The easiest way is to listen to componentDidMount, perform your ajax request, and then set the state.

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

    You can read more about the component lifecycle here: https://facebook.github.io/react/docs/react-component.html

    • Note that this example doesn't handle for the fact of your component being unmounted before the XHR request finishes. Out of simplicity's sake, not including it here.

提交回复
热议问题