如何用React Native从api加载数据
How to load data from an api with React Native
我正在从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);
});
希望有帮助!
相关文章:
- Google Map JS API-加载地图分幅,但所有图像(标记、缩放控制等)都不加载;t负载2分钟
- 使用JavaScript和Twitter API加载推文
- 如何使用谷歌地图api加载带有当前地址的地图
- YouTube Javascript API:加载在 Firefox 中不起作用
- 谷歌地图 API 加载问题
- 谷歌地图API加载缓慢,有许多标记
- JWPlayer在使用API加载方法时无法在iPad / iPhone上播放
- 在使用 KnockoutJS 从 API 加载字段后,将字段添加到 observableArray
- Rails & Youtube API:加载 iframe 时出现问题
- Vimeo API - 加载视频
- 仅从Google API加载特定字体
- 关于使用YouTube播放器API加载播放列表
- 谷歌地图Javascript API加载不正确
- 当应用程序从图形api加载时,如何获得应用程序的用户
- 谷歌地图API加载了一秒钟,然后说检查js控制台,但没有警告或错误,任何想法
- 使用API加载YouTube视频
- Ember.js从API加载简单数据
- 如何用Realtime API加载现有的大型数据模型?
- 错误:[ng:areq]试图从WEB API加载数据
- 如何告诉谷歌地图API加载脚本在React组件中寻找回调