2017-06-20 99 views
0

如何在提取API时设置超时时间?React Native - 提取时的超时时间

我想要的只是试图抓取数据10秒钟,如果失败,那么我想从AsyncStorage加载数据(以前保存并且每次更新时都会更新)。

大概我怎么做这不是正确的方式,我有点在编程xD noob但是这段代码在模拟器上工作得很好,但不能在我的手机(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

[如何将setTimeout添加到使用redux的提取承诺?](https://stackoverflow.com/questions/38512238/how-to-add-a-settimeout-to-a-fetch- promise-that-uses-redux) –

回答

0

RN使用没有超时的whatwg-fetch。你可以通过使用whatwg-fetch-timeout来解决它,如上所述here

这会比上面链接的评论中的Micheal更简单,它使用Promise.race和setTimeout。诚然,相当聪明。

+0

嗨, 我用这个库代替:https://github.com/robinpowered/react-native-fetch-polyfill - 因为我没有理解如何使用你所说的,对不起:/ 有了这个库的超时工作,但有一个问题,当提取,如果它在开始时失败,他跳到catch,并且我想要的是等到我定义pass的时间,然后跳转到赶上...我怎么能做到这一点? – Proz1g

+0

我懂了!不管怎么说,还是要谢谢你 ;) – Proz1g