再次运行componentDidMount函数React Native

时间:2019-03-02 22:02:32

标签: react-native

我尝试从服务器获取信息,而获取未完成的show search组件,而获取完成后显示的信息...一切正常...但是,当NET脱机显示搜索组件并打开NET时,我想显示一个按钮“再试一次”,然后单击“ FetchData”功能再次运行。

constructor(){
    super();
    this.state={
      isLoading:true,
      dataSource:null,
      dataError:false
    }
}
componentDidMount(){
FetchData = () => {
  return fetch(SuperUrl+'/info')
  .then((response)=>response.json())
  .then((responseJson)=>{
      this.setState({
      isLoading:false,
      dataSource: responseJson
    })
  })
  .catch((error)=>{this.setState({dataError:true})})
}
FetchData()
}



 render() {
if(this.state.dataError)
{
<View>
<Buttom onpress={()=>{FetchData()}}>
<Text>Try Again</Text>
<Button>
</View>
}
if(this.state.isLoading)
{
  return(
  <Container>
  <StatusBar backgroundColor={'#3949ab'}/>
      <Searching/>
  <JaFooter list={{backgroundColor:'#3949ab', color:'#ffffff'}}/>
  </Container>
  )
}
else
{
  let regionName = this.state.dataSource.map((value,key)=>{
    return(
        <ListItem key={key} >
        <Text key={key} style={styles.cityName}>{value.name}</Text>
        </ListItem>
    )
  })

1 个答案:

答案 0 :(得分:0)

您的标题很容易引起误解,因为componentDidMount应该运行一次。您想要的完全不同,所以我会解释。由于您要求的是与RN模式不符的内容,因此有可能使答案封闭。反正..

提取本身不支持超时。但是您可以通过执行两个承诺来解决此问题。一个用于获取,另一个用于超时。这是伪代码,您将必须了解Promise.race以及setTimeout的工作方式。

const promise1 = fetch;
const promise2 = new Promise((resolve, reject) => {
     setTimeout(() => reject(new TimeoutError()), 30000);
})

Promise.race([promise1, promise2])
.then(() => {
  //You got a response from the server
})
.catch(err => {
   //Probably timeout
    if (err.code == 'Timeout')
         this.setState({loading: false, showTryAgain: true})
})

Promise.race将同时运行,但是如果网络获取的请求首先结束,它将忽略您想要的超时。