2016-08-11 30 views
0

我從api加載圖像,我將實現到網格中。雖然我的圖像未顯示,因爲它們未定義。以下是我的組件的一些功能。圖像和isLoading在構造函數中都被定義爲一個空數組和true。如何正確加載數據本機

componentWillMount() { 
api().then((res) => { 
this.state.images.push(res); 
}).done(); 

this._load10Images(); 
this.setState({isLoading:false}); // is loading is set to false 
}         // after images loaded. 

_getImageUrls(){ 
api().then((res) => { 
this.state.images.push(res); 
console.log(this.state.images); //right here works array is growing 
console.log(this.state.images[0]);//with image uris 
}).done(); 
} 

_load10Images(){ 
for(let i=0; i<10; i++){ 
this._getImageUrls(); //call _getImageUrls 10 times to fill array 
} 


} 

_loadImageGrid(){ 

    if(this.state.isLoading){ 
return <Text>Loaading ...</Text> 
} 
else{ 
console.log(this.state.images[0]); // coming back as undefined 
return <Text>not loading ...</Text> 
    } 
} 

render(){ return <View> 
     {this._loadImageGrid()} 
     </View> 
    } 

在渲染函數和_loadImageGrid函數中,圖像數組返回時未定義。

+0

更改狀態屬性是你沒有意義的。你需要使用setState來觸發一個新的渲染過程。 – flq

+0

@flq我想我明白你在說什麼,你能否詳細說明一下? –

+0

哈哈,看到答案:) – flq

回答

1

我想補充以下功能:

constructor(props) { 
    super(props); 

    this.state = { 
     images: [] 
    } 

} 
_addImage(image) { 
    let images = Object.assign([], this.state.images); 
    images.push(image); 
    this.setState({images}); 
} 

然後你可以使用它像這樣

api().then((res) => { 
    this._addImage(res); 
}); 

希望它能幫助!

相關問題