获取
API 时如何设置超时?
我确切地想要的是尝试获取数据 10 秒,如果失败,那么我想从 AsyncStorage 加载数据(以前保存并在每次获取工作时更新(。
可能我这样做的方式不正确,我有点擅长编程 (xD(。但是,此代码在模拟器上工作正常,但在我的手机(android(上不起作用。异步存储似乎不起作用。
这是我的代码:
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
})
}
}
))
}
希望你能帮助我。谢谢!
RN 使用没有超时的 whatwg-fetch。你可以通过使用 whatwg-fetch-timeout 来解决它,如此处所述
这将比上面Micheal在链接的评论中更简单,即使用Promise.race和setTimeout。诚然,相当聪明。