2017-02-07 23 views
0

我從我的數據庫中提取數據,需要在組件安裝之前可用,以便頁面填充componentDidMount()生命週期方法。我已經驗證過,如果我刪除了setState和console.log數據,它將按照預期從數據庫中提取數據,但是當我嘗試將數據分配給狀態變量時,它會在我的componentWillMount()生命週期方法內返回一個錯誤,指出Unable to get property 'setState' of undefined or null reference 。我在下面列出了我的ReactJS代碼。未定義的狀態時拉動數據安裝

import React, { Component, PropTypes } from 'react'; 
import Picture from '../../components/picture.jsx'; 
import { browserHistory } from 'react-router'; 
export default class Products extends Component { 

    constructor(props) { 
     super(props); 
     this.state = {clothingData: ''}; 
    } 

    componentWillMount(){ 
      fetch('/t') 
      .then(function(result){ 
       return result.json(); 
      }) 
      .then(function(re){ 
       this.setState({ clothingData: re }); 
       console.log(this.state.clothingData); 
      }) 
      .catch(function(error){ 
       console.log(error); 
      }); 
    } 

    componentDidMount(){ 

     //empty for now 
    } 

    render(){ 
     var MyArray = ['justin','tiffany','joe','john','karissa','pam','joseph','sean','kim']; 
     var imageSrc = ['http://placehold.it/249x373','http://placehold.it/249x373','http://placehold.it/249x373','http://placehold.it/249x373','http://placehold.it/249x373', 
         'http://placehold.it/249x373', 'http://placehold.it/249x373', 'http://placehold.it/249x373']; 

    return (
     <div> 
     <Picture src = {imageSrc} onClick = {() => {browserHistory.push('/Product'); }} name = {MyArray} amount = {8} /> 
     </div> 
); 
} 
} 

回答

1

問題是this正在從組件實例的功能實例/全局對象重新分配。

componentWillMount() { 
    fetch('/t') 
    .then((result) => { 
     return result.json(); 
    }) 
    .then((re) => { 
     this.setState({ clothingData: re }); 
     console.log(this.state.clothingData); 
    }) 
    .catch(function(error){ 
     console.log(error); 
    }); 
} 

會工作得很好,因爲箭頭功能將確保this被綁定到組件實例,以便this.setState實際上將被定義。而你有this被設置爲全局對象,它沒有屬性setState

+0

謝謝!我知道我的代碼在正確的軌道上,我認爲通過使用反應生命週期方法它會繼承「this」,所以我甚至沒有考慮過這個問題。謝謝 –