【发布时间】:2017-11-23 04:08:04
【问题描述】:
如何在获取 API 时设置超时?
我真正想要的是尝试获取数据 10 秒,如果失败,那么我想从 AsyncStorage 加载数据(之前保存并在每次获取工作时更新)。
可能我这样做不是正确的方法,我在编程方面有点菜鸟 (xD)。但是,此代码在模拟器上运行良好,但在我的手机(android)上不起作用。 AsyncStorage 似乎不起作用。
这是我的代码:
constructor(){
super()
this.state = {
fetching: false,
data: []
}
}
componentWillMount(){
this.setState({ fetching: true })
fetch('http://192.168.1.122:3000/categories.json')
.then(res => res.json())
.then(res => {
this.setState({
data: res,
fetching: false
})
})
.then(res => {
AsyncStorage.setItem(
'@Data:Monumentos',
JSON.stringify(res)
)
})
.catch(AsyncStorage.getItem(
'@Data:Monuments',
(err, dados) => {
if(err) {
console.error('Error loading monuments', err)
} else {
const monuments = JSON.parse(dados)
this.setState({
data: monuments
})
}
}
))
}
希望你能帮助我。谢谢!
【问题讨论】:
标签: react-native react-native-android react-native-ios