首页 > 解决方案 > 如何在 React Native 中构造来自 api 的返回数据?

问题描述

我正在使用 React Native react-native-snap-carousel,它只显示带有图像、标题和副标题的轮播。数据通过静态文件加载:

export const ENTRIES2 = [
  {
      title: 'Favourites landscapes 1',
      subtitle: 'Lorem ipsum dolor sit amet',
      illustration: 'https://i.imgur.com/SsJmZ9jl.jpg'
  },
  {
      title: 'Favourites landscapes 2',
      subtitle: 'Lorem ipsum dolor sit amet et nuncat mergitur',
      illustration: 'https://i.imgur.com/5tj6S7Ol.jpg'
  }
]

我已经设置 axios 来从 api 检索数据:

axios.get('http://192.168.1.1/test')
      .then(function (response) {
        console.log(response);
        console.log(response.data);
        this.isLoading = false;
      })
      .catch(function (error) {
        console.log(error);
        this.error = error
        this.isLoading = false;
      });

如何使用此返回的数据创建与静态文件类似的 const 结构?

谢谢

标签: reactjsreact-nativeconstantsaxios

解决方案


查看 react-native-snap-carousel 文档,您可以看到道具“数据”是一个数组,如下所示。

return (
     <Carousel
          ref={(c) => { this._carousel = c; }}
          data={this.state.entries} <-- it's a array
          renderItem={this._renderItem}
          sliderWidth={sliderWidth}
          itemWidth={itemWidth}
         />
 );

因此,在您的组件中创建一个状态将接收来自 api 的数据。

state = {
    data: []
}

并使用 axios 来检索 componentWillMount 中的数据。

componentWillMount() {
   axios.get('http://192.168.1.1/test')
      .then(function (response) {
        console.log(response);
        console.log(response.data);

        this.setState({
            data: response.data
        }) 

        this.isLoading = false;
      })
      .catch(function (error) {
        console.log(error);
        this.error = error
        this.isLoading = false;
      });
}

推荐阅读