【发布时间】:2016-08-11 21:45:17
【问题描述】:
我正在从 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 函数中返回为未定义。
【问题讨论】:
-
像你一样改变状态属性是没有意义的。您需要使用 setState 来触发新的渲染通道。
-
@flq 我想我明白你在说什么,你能详细说明一下吗?
-
哈哈,看答案:)
标签: javascript api reactjs react-native