【问题标题】:How to structure returned data from an api in React Native?如何在 React Native 中构造来自 api 的返回数据?
【发布时间】:2018-06-07 00:33:46
【问题描述】:

我正在使用 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?

谢谢

【问题讨论】:

  • “const 结构化”是什么意思?你是说州吗?
  • API 返回的数据是什么形状的?响应的输出是什么?

标签: reactjs react-native constants axios


【解决方案1】:

这很简单!您可以根据需要设置对象。我假设 response.data 是此处的条目数组,但您必须修改您的响应使用的任何内容。

axios.get('http://192.168.1.1/test')
  .then(function (response) {
    console.log(response.data);
    let data = []
    response.data.forEach(entry => {
      data.push({
        title: entry.title,
        subtitle: entry.subtitle
      })
    })
    this.isLoading = false
  })

如果此方法在您的组件中(如在componentDidMount 中),您可以使用setState 将数据添加到您的状态,然后在您的组件中使用。

...
  subtitle: entry.subtitle
})
this.isLoading = false
this.setState({data})

然后在你的渲染方法中:

render () {
  const {data} = state
  return(
    <FlatList
      data={data}
      renderItem={({item}) => <Text>{item.title}</Text>}
    />
  )
}

这里的关键是根据您的 api 调用返回的内容创建元素数组,然后将它们保存到组件的状态中,您可以访问该状态来呈现它们。

【讨论】:

  • 从现有数组构建新数组时,使用map()
【解决方案2】:

查看react-native-snap-carousel文档,可以看到prop“data”是一个数组,如下图。

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 来检索组件WillMount 中的数据。

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

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 2021-11-04
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多