javascript - 如何在没有互联网的情况下进行重定向
问题描述
我有一个让我头疼的问题
我在 React 中创建了我的网页,它检测到没有互联网或没有连接到服务器的时间,一旦发生这种情况,就会执行一个操作,我想要做的这个操作是重定向到我的主页而不停止查看界面网站并继续离线操作页面
Javascript的所有重定向,例如
window.location.href / replace / assign 不起作用,我认为这是因为它通过 URL 重定向,为此您需要连接。
我正在使用反应,这是我目前用来进行重定向的一个,其中新位置将覆盖历史堆栈中的当前位置,此组件无需互联网即可在站点内移动,但这仅在我触摸时有效链接到此操作的按钮。但我想要的是让这个动作自动完成。
window.setInterval(function () {
axios.get('https://roraso.herokuapp.com/User/CurrentUser',
{ headers: { 'access-token': localStorage.getItem('access-token')}})
.then(res => {
if(localStorage.getItem('status') === 'offline'){
localStorage.setItem('status', 'online');
Swal.fire({
title: 'Reconected',
text: 'Online Mode',
type: 'success',
})
return window.location.href = "/";
}
})
.catch(err => {
if(localStorage.getItem('status') === 'online'){
localStorage.setItem('status', 'offline');
Swal.fire({
title: 'No connection detected',
text: 'Offline Mode',
type: 'error',
confirmButtonText: 'Aceptar'
}).then((result) => {
if (result.value) {
return <Redirect to='/' />
}
})
}
})
}, 7000);
这也是检测与服务器或互联网连接的代码,但它不起作用。我没有更多的想法让这个重定向工作
谢谢
解决方案
我找到了解决我的问题的方法。
我通过使用带有路由器的 HOC 导出我的类来解决它,这允许我访问历史并使用重定向 props.history.push ('/')
checker_status(props){
window.setInterval(function () {
axios.get('https://roraso.herokuapp.com/User/CurrentUser',
{ headers: { 'access-token': localStorage.getItem('access-token')}})
.then(res => {
if(localStorage.getItem('status') === 'offline'){
localStorage.setItem('status', 'online');
Swal.fire({
title: 'Reconected',
text: 'Online Mode',
type: 'success',
})
props.history.push('/')
}
})
.catch(err => {
if(localStorage.getItem('status') === 'online'){
localStorage.setItem('status', 'offline');
Swal.fire({
title: 'No connection detected',
text: 'Offline Mode',
type: 'error',
confirmButtonText: 'Aceptar'
}).then((result) => {
if (result.value) {
props.history.push('/')
}
})
}
})
}, 7000);
}
componentWillMount(){
this.checker_status(this.props);
}
export default withRouter(myClass);
推荐阅读
- python - 查找具有已定义 x 值的最大值的函数
- azure - 使用插入在 Azure sql db 中出现严重错误
- android - textIsSelectable 不适用于 descendantFocusability=blocksDescendants
- php - 构建具有 WinSSL、NTLM、HTTP2、SSH2 和 IPv6 支持的工作 libcurl
- ruby-on-rails - 使用 Redis、Sidekiq、Heroku 和 Rails 5 了解后台工作者
- python-2.7 - 如何让游戏在 30 秒后停止?
- javascript - 本教程是什么意思?在 Expo 中使用 create-react-native-app
- c - 改进递归哈达玛变换
- html - 为什么我的下拉菜单只允许我单击菜单中的第一项?
- sql - R:按月计算的过去 365 天窗口中的总计