2016-08-11 72 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); 
}); 

希望它能帮助!

相关问题