react-native - 再次运行 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>
)
})
解决方案
您的标题非常具有误导性,因为 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 将并行运行,但如果网络请求首先结束,它将忽略您想要的超时。
推荐阅读
- reactjs - 无法设置默认值
组件 - redux 表单 - c++ - 异常处理级别/重新抛出异常
- c - 如何使用 int 作为指针的地址?
- blogger - 博主特别标签
- java - 无法将参数从 maven 命令传递到 Testng Runner
- flutter - flutter run -bash: Desktop/flutter/bin/flutter: 没有这样的文件或目录
- vue.js - 格式化程序列 - Bootstrap-vue - VueJS
- bash - bash 多行命令到变量只导致第一行
- reactjs - react-calendar 如何更改默认日期格式并禁用旧日期
- java - Java 日期转换为字符串并返回日期,相等性检查失败