2017-07-19 193 views
0

我試圖通過componentDidMount生命週期方法進行簡單的獲取。但是,除非我有一秒鐘超時,否則結果不會顯示在頁面上。我收集這是由於獲取的異步性質,但我怎樣才能解決這個問題,而不必使用setTimeoutcomponentDidUpdate工作/你將如何使用它?React生命週期方法:在componentDidMount中獲取

 constructor(props) { 
     super(props); 
     this.state = { value: '' }; 
     this.getValue= this.getValue.bind(this); 
     } 

     getValue() { 
      return (
       fetch(url, { 
        method: 'GET', 
       }).then(response => { 
        if (response.status >= 400) { 
         throw new Error('no response: throw'); 
        } 
        return response.json() 
       }).then(response => { 
        this.setState({value: response}); 
       }).catch((error) => { 
        this.setState({ 
         value: 'no response: catch' 
        }) 
       }) 
      ); 
     } 


    componentDidMount(){ 
     //this.getValue(); //does not work 
     setTimeout(() => this.getValue(), 1000); //this works & populates page 
    } 


    render() { 
      return (
        <div> 
        <div>{this.state.value}</div> 
        </div> 
      ) 
    } 

回答

0

確保您將您的this.getValue方法綁定到構造函數中的正確上下文中。當你把它放在你的setTimeout中時,你可以用一個胖箭頭函數來隱式地綁定到this

constructor(props) { 
    super(props); 
    this.getValue = this.getValue.bind(this); 
} 

getValue() { ... } 

componentDidMount() { 
    this.getValue(); 
} 
+0

這是正常的方法調用,不需要綁定.. :) –

+0

你是什麼意思? 'this.setState'需要'this'綁定到組件實例。他的代碼段沒有顯示出發生的地方,並且在寫入時他從'fetch'的上下文中調用它。 –

+0

檢查此答案,您將瞭解何時以及爲何需要綁定。 [**鏈接**](https://stackoverflow.com/a/41391426/5185595):) –

相關問題