【问题标题】:React Native - Timeout on fetchingReact Native - 获取超时
【发布时间】: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


【解决方案1】:

RN 使用没有超时的 whatwg-fetch。您可以使用 here 提到的 whatwg-fetch-timeout 来解决它

这将比上面链接的 cmets 中的 Micheal 更简单,即使用 Promise.race 和 setTimeout。不可否认,相当聪明。

【讨论】:

  • 嗨,我改用了这个库:github.com/robinpowered/react-native-fetch-polyfill - 因为我不明白如何使用你说的那个,抱歉:/ 使用这个库超时有效,但是有一个问题,当抓取,如果一开始就失败了,他会跳到catch,我想要的是等到我定义的时间过去,然后再跳到catch……我怎么能做到这一点?
  • 我明白了!无论如何谢谢;)
猜你喜欢
  • 2018-06-09
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多