[英]How to load data from an api with React Native
我正在從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);
});
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.