gpt4 book ai didi

javascript - 如何在 React Native 中设置 axios 的休息状态

转载 作者:太空宇宙 更新时间:2023-11-03 22:23:52 25 4
gpt4 key购买 nike

我想从API读取数据数组,我在react Native代码中使用axios,但状态首先返回空数组,然后返回所有索引。那么我如何设置响应的状态?

constructor(props) {
super(props);
this.state = {
categories: []
}
}
loadData = () => {
axios.get("http://my-fashion.co.il/samerjammal_APIs/api/categories")
.then((res) => {
console.log('data from api', res.data.data[0].imageURL)
this.setState({
categories:res.data.data
})
})
}

componentDidMount(){
this.loadData();
}

这是组件:

  <Image
source={this.state.categories[0].imageURL}
style={{
resizeMode: "cover",
maxHeight: deviceHeight / 2,
flex: 1,
width: null,
height : 305
}}
/>

请问有什么帮助吗?我尝试使用 self,但也不起作用:(

最佳答案

获取数据后需要再次渲染。添加加载指示器和捕获获取错误的方法也是一个好主意。

constructor(props) {
super(props);
this.state = {
categories: [],
loading: true,
}
}
loadData = () => {
axios.get("http://my-fashion.co.il/samerjammal_APIs/api/categories")
.then((res) => {
console.log('data from api', res.data.data[0].imageURL)
this.setState({
categories:res.data.data,
loading: false,
})
})
}

componentDidMount(){
this.loadData();
}

render() {
const { categories, loading } = this.state;

return (
<View style={{
maxHeight: deviceHeight / 2,
flex: 1,
width: null,
height : 305
}} >
{ loading ? <ActivityIndicator style={StyleSheet.absoluteFill} size=“large” /> : (
<Image
source={categories[0].imageURL}
style={{
resizeMode: "cover",
...StyleSheet.absoluteFillObject,
}}
/>
)
}
</View> )}

关于javascript - 如何在 React Native 中设置 axios 的休息状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49692149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com