首页 > 解决方案 > 再次运行 componentDidMount 函数 React Native

问题描述

我尝试从服务器获取信息,同时获取未完成的显示搜索组件,当获取完成显示信息时...一切正常...但是当 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>
    )
  })

标签: react-native

解决方案


您的标题非常具有误导性,因为 componentDidMount 应该运行一次。你想要的完全不同,所以我会解释。由于您要求的内容与 RN 的模式背道而驰,因此您冒着被关闭答案的风险。反正..

Fetch 本身不支持超时。但是你可以通过运行两个 Promise 来解决它。一个用于获取,另一个用于超时。这是伪代码,你必须了解 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 将并行运行,但如果网络请求首先结束,它将忽略您想要的超时。


推荐阅读