我正在从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>
}
图像数组在render函数和_loadImageGrid函数中以未定义的形式返回。
我将添加以下功能:
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);
});
希望能帮助到你!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句