2017-10-17 28 views
0

請問我的反應類,我試圖更新我的狀態,但我得到這個錯誤「無法讀取屬性setState的未定義」..我已經嘗試每一個解決方案在線,但沒有運氣'this.setState'有什麼問題

這裏是代碼

export default class PageBackground extends Component{ 
    constructor(props) { 
      super(props); 

      this.state={ 
       lat   :'nothing', 
       longi  :'' 
      }; 
      this.getLocation=this.getLocation.bind(this); 
      } 


     componentWillMount() { 
      this.getLocation(); 
     } 
     getLocation() { 

      fetch('http://freegeoip.net/json/') 
      .then((res)=>res.json()) 
      .then(function (objec){this.setState({lat:objec.latitude,longi:objec.longitude});}) 
      .catch((err)=>console.log("didn't connect to App",err)) 
      console.log(this.state.lat) 
     } 

     render(){ 
      return(
       <p>{this.state.lat}</p> 
       ) 
      } 
     } 
+0

您是否獲得控制檯日誌? – buoyantair

+0

我認爲'this'是在函數的上下文中。也許你應該嘗試'that = this'和'that.setState' – AnkitG

+0

有litterally一百萬重複這個非常錯誤。我很驚訝你沒能找到他們中的任何一個。 – Chris

回答

5

function() { ... }語法不會維持從上下文this參考。使用箭頭函數:

then(() => { 
    this.setState({lat: objec.latitude, longi: objec.longitude}) 
}) 

另一種選擇是function() { }後添加.bind(this)

或者,只保存this一個局部變量,並用它在函數內部:

var self = this; 
fetch('http://freegeoip.net/json/') 
     .then((res)=>res.json()) 
     .then(function (objec){self.setState({lat:objec.latitude,longi:objec.longitude});}) 
     .catch((err)=>console.log("didn't connect to App",err)) 
     console.log(this.state.lat) 

然而,箭頭功能都是一模一樣介紹了這樣那樣的問題。

+0

非常感謝你。這工作,但我想知道爲什麼?我閱讀箭頭功能不能很好地與'這'''爲什麼這種情況不同? –

+0

爲什麼我們甚至必須綁定我們在構造函數中創建的es6類中的所有方法? –

+1

@JohnAnisere第一個問題的答案是箭頭函數從周圍的代碼中捕獲'this',因此您不必手動將'this'綁定到它們。他們以你期望的方式工作。另一個問題更復雜。當類方法用作「鬆散」(第一類)函數時,您正在討論這個問題。這些方法不會自動綁定到它們的實例,而必須手動綁定。 – Sulthan

1

嘗試了這一點:

getLocation() { 
      var self = this; 
      fetch('http://freegeoip.net/json/') 
      .then(function (objec) { 
       console.log(objec); 
       self.setState({lat: objec.latitude, longi: objec.longitude}) 
      }) 
      .catch(function (error) { 
       console.log(error); 
      }); 
     } 
1

這裏的問題是,你想在不同的範圍accesss this

每當我們通過一個function() {}作爲回調,它會創建它自己的範圍。 改爲使用箭頭函數。

() => { 'your code here'; } 

箭頭函數共享其父項的範圍。

getLocation =() => { 
    fetch('https://freegeoip.net/json/') 
     .then(res => res.json()) 
     .then((objec) => { 
      this.setState({ lat: objec.latitude, longi: objec.longitude }); 
     }) 
     .catch(err => console.log("didn't connect to App", err)); 
    console.log(this.state.lat); 
} 
+0

非常感謝你.. –