2017-09-26 16 views
0

私はReactを学んでいるので、私と穏やかで、私は新人です。React - Reactコンポーネントの変数を使用しているエラー

import React from 'react'; 
import HttpHandler from './../services/HttpHandler'; 
import Podcast from './Podcast/Podcast'; 

class Master extends React.Component{ 
    constructor(){ 
     super(); 
     this.api = new HttpHandler(); 
     this.podList = this.api.getAllPodcasts(); 
     this.http = ""; 
     this.api.getHttpResponse(function(responseData){ 
      var datos = responseData; 
      this.http = datos; 
     }, function(error){ 
      this.http = error; 
     }); 
    } 

    render(){ 
     return (
      <div> 
       <h1>Master</h1> 
       <ul> 
        {this.podList.map((podcast) => <li>{podcast}</li>)} 
       </ul> 
       <p>API Response: {this.http}</p> 
      </div> 
     ); 
    } 
} 
// ======================================== 

export default Master; 

このコンポーネントが使用するのHttpHandler起動とクラッドのXMLHttpRequest GET:私は、このコンポーネントを持っています。応答がうまくいったら、コールバック関数を実行し、応答を処理しようとするとき以外はすべて完璧です。this.httpは未定義で、TypeError: undefined is not an object (evaluating 'this.http = datos')があります。私は悪い変数宣言を持っていることは明らかですが、それは実現する方法でしょうか?

答えて

0

REST要求への応答を表す場合は、Reactの状態をユーザーに提示する必要があります。これを行う最善の方法はcomponentDidMountです。あなたはcomponentDidMountでhttpリクエストになるだろう、そして、

constructor(){ 
    super(); 
    this.state={ 
     http: "", 
    } 
} 

:あなたのコンストラクタは次のようなものでなければなりません

componentDidMount(){ 
    let api = new HttpHandler(); 
    let podList = api.getAllPodcasts(); 
    let http = "" 
    var that = this; 
    api.getHttpResponse(responseData =>{ 
     let datos = responseData; 
     that.setState({ 
      http: datos, 
     }); 
    }, function(error){ 
     that.setState({ 
      http: error, 
     }); 
    }); 
} 

最後に、あなたのrenderメソッドでは、あなたは状態の属性のhttpアクセス:

<p>API Response: {this.state.http}</p> 

これはReactで行う方法です。最初のレンダリングでは、httpが空になり、componentDidMountに更新され、setStateが自動的に再レン​​ダリングをトリガーします。

+0

に使用矢印機能を、それが新しいこの内部(ES6)を作成won'tよう

const _this = this; this.api.getHttpResponse(()=>{ this === _this // true }); 
  • バインドこの私が理解すると思います今すぐまだエラーが出ていますが、今回は 'TypeError:undefinedは(this.setState 'を評価する)オブジェクトではないので、' getHttpResponse() 'の中の無名関数を参照している可能性があります?? – LordVermiis

  • +0

    これはスコープ上の問題であり、getHttpResponseを呼び出す前に 'var that = this'を追加して解決しました。そして、' that.setState'の中にあります。正しい応答としてマークするために、あなたの応答でそれを変更してください。そして、あなたは歓迎です! – LordVermiis

    +0

    はい、私はそれについて忘れていました:)問題はありませんが、状態はReactの最も重要で紛らわしい(少なくとも最初は)側面です。また、アプリケーションが大きくなった場合は、[Redux](http://redux.js.org/docs/introduction/)をチェックしてください。 –

    関連する問題