我即将改进我的第一个react原生应用程序,我想在超时时显示一个重试/重新加载按钮。例如,Web服务在5秒内没有响应,我抛出了一个问题。但现在我想给机会重新加载屏幕。我已经尝试创建一个刷新方法并使用setState,但没有成功。我想我需要再次启动渲染方法吗?
render() {
if (this.state.connection === true) {
return (
<Login />
)
else {
<View style={styles.errorConnection}>
<Text>Error, no Connection</Text>
<Button title="reload" />
</View>
}
}
...
componentDidMount() {
this.checkConnection();
}
checkConnection = async () => {
let x = await new connection().checkConnection();
this.setState(connection:x);
}
你没有问具体的问题,我不能给出具体的答案,但给你。欢迎在评论中提问:(
class SomeComponent extends React.Component {
state = {
requestFailed: false,
}
constructor(props) {
super(props);
// This line is very important if you don't know why ask
this.handleRetry = this.handleRetry.bind(this);
}
render() {
return (
<>
<Text>This is some very important stuff here</Text>
{this.state.requestFailed && (
<Button title="Try Again" onPress={this.handleRetry}
)}
</>
)
}
handleRetry() {
this.fetch();
}
fetch() {
fetch('your.url.url')
.then()
.catch(() => this.setState({requestFailed: true}))
}
}