React Native - 获取时超时

时间:2017-06-20 14:34:59

标签: react-native react-native-android react-native-ios

如何在获取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
            })
        }
     }
   ))
}
希望你能帮助我。谢谢!

1 个答案:

答案 0 :(得分:0)

RN使用whatwg-fetch,它没有超时。您可以使用提到的here

中的whatwg-fetch-timeout来解决此问题

这比使用Promise.race和setTimeout的注释中的Micheal更简单。不可否认,非常聪明。

相关问题