如何用React Native从api加载数据

How to load data from an api with React Native

本文关键字:api 加载 数据 Native 何用 React      更新时间:2023-09-26

我正在从api加载图像,我将实现到网格中。我的图像虽然没有被显示,因为它们是未定义的。这是我的分量的一些函数。Images和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函数中,图像数组返回为未定义。

我将添加以下函数:

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);
});

希望有帮助!