【问题标题】:How to load data from an api with React Native如何使用 React Native 从 api 加载数据
【发布时间】: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


【解决方案1】:

我会添加以下功能:

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

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2020-04-16
    • 2018-06-11
    • 2020-12-18
    相关资源
    最近更新 更多