2017-08-15 23 views
1

私は反応で非同期XMLHttpRequestを実装しようとしています。 は、ここに私の試みです:私はそれにリスナーを追加することを考えてきた非同期xmlhttp要求の反応

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

あなたは 'axios'または' fetch'を使うべきです。 – Purgatory

+0

私は以前の回答から得た返信に本当に満足していますが、入力に感謝します。 – Mac

答えて

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>

1

私はcomponentDidMountライフサイクルイベントに接続してリクエストすることをおすすめします。次に、完了したらsetStateに電話して、コンポーネントを再レンダリングする状態を更新します。

https://www.youtube.com/watch?v=YpM3YK9Uue0

+0

うーん、試してみるよ。 – Mac

1

あなたが反応のライフサイクルの中にAJAXリクエストを実行する必要があります。最も簡単な方法は、componentDidMountを聞いて、あなたのajaxリクエストを実行してから、状態を設定することです。

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 <img src={this.state.data[0].url}></img> 
    } 
    else { 
     return <div>Loading...</div> 
    } 
    } 
} 

あなたがここにコンポーネントのライフサイクルに関する詳細を読むことができます: https://facebook.github.io/react/docs/react-component.html

  • この例では、あなたのコンポーネントがXHRリクエストが終了する前にアンマウントという事実のために処理しないことに注意してください。シンプルさのためにここには含まれていません。
2

ライフサイクルメソッドcomponentDidMountでAJAXコールを行うことをお勧めします。

componentDidMountは副作用のためです。イベントリスナー、AJAX、DOMの変異などを追加する

また、新しいfetch APIの使用を検討する必要があります。

class Welcome extends React.Component { 
    constructor() { 
    this.state = { 
     data: null, 
    }; 
    } 

    componentDidMount() { 
    fetch('https://jsonplaceholder.typicode.com/photos/').then(res => { 
     return res.json() 
    }).then(res => { 
     this.setState({ data: res}); 
    }).catch(err); 
    } 

    render() { 
    if (this.state.data) { 
     return <img src={this.state.data[0].url}></img> 
    } 
    else { 
     return <div>Loading...</div> 
    } 
    } 
} 
関連する問題