reactjs - 如何在 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 结构?
谢谢
解决方案
查看 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;
});
}
推荐阅读
- javascript - 比较对象 JavaScript 的值
- laravel - 使用 Laravel Sanctum 向 Horizon 添加身份验证
- arrays - 为什么 numpy 在比较两个数组中的元素较大值时不会更快?
- visual-studio-code - 有没有办法只撤消 vscode 中的一行?
- r - 有没有办法使用 Quantmod 从矩阵中提取元素?
- typescript - 为什么我不能在打字稿类的构造函数中访问抽象属性
- swift - 将字典转换为数组并访问值 Swift 之一
- css - 子元素的正确样式
- c++ - c ++设计(多重继承与列出相关数据)
- python - 您能否解释一下范围内的 d(arr-1,0,-1)(什么是 0 和 -1)?