2017-09-26 71 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 clads啓動一個XmlHttpRequest GET。在成功響應時,我執行回調函數,除了當我嘗試處理響應時,所有的都是完美的,var this.http未定義,我得到TypeError: undefined is not an object (evaluating 'this.http = datos')。很明顯,我有一個不好的變量聲明,這將實現的方式?

回答

0

如果您想要表示對REST請求的響應,您應該使用React的狀態。最好的方法是componentDidMount。你的構造應該是這樣的:

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

然後,你會做出componentDidMount 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, 
     }); 
    }); 
} 

最後,在你的渲染方法,您可以訪問狀態的屬性HTTP:

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

這是在React中完成它的方法。在第一個渲染中,http將是空的,然後在componentDidMount它將被更新並且setState將自動觸發重新渲染。

+0

我想我理解剛纔的狀態。仍然得到錯誤,但是這次'TypeError:undefined不是一個對象(評估'this.setState')',這可能是引用了'getHttpResponse()'中的匿名函數。 – LordVermiis

+0

的確如此,這是一個範圍問題,我在調用getHttpResponse和內部的'that.setState'之前解決了它添加'var that = this'的問題。請在您的回覆中更改它以標記爲正確的回覆。歡迎您! – LordVermiis

+0

是的,我忘記了:)沒問題,狀態既是最重要的,也可能是令人困惑的(至少在最初)React的方面。此外,如果您的應用程序增長,您應該查看[Redux](http://redux.js.org/docs/introduction/)。 –

-1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

TL;博士問題:

const _this = this 
this.api.getHttpResponse(function(){ 
    this === _this // false 
}); 

可選的解決方案

  1. 在較高的範圍內分配這_this,並用它在回調中

  2. 使用箭頭功能,所以它那倒創建一個新的這裏面(ES6)

    const _this = this; 
    this.api.getHttpResponse(()=>{ 
        this === _this // true 
    }); 
    
  3. 綁定這個回調(ES5)

    var _this = this 
    this.api.getHttpResponse(function(){ 
        this === _this // true 
    }.bind(this))` 
    
相關問題