首页 > 解决方案 > React Router-根据浏览器类型路由不同的页面

问题描述

我正在为客户构建一个网站,只有当用户使用移动浏览器时,我才需要能够路由到一个页面。如果用户不在移动浏览器上,则会显示一个模式弹出窗口。目前,如果用户在桌面上,我可以检测浏览器类型并打开模式,但如果用户在移动设备上,我无法路由页面。

这是我当前的函数代码,它从 index.js 传递到带有按钮的组件,该按钮将 swapContactModal 函数分配为 onClick。

如果用户在桌面上单击此按钮,它会成功地将本地状态值交换为模态,并显示它。但是, hist.push 将地址“/testimonials”推送到地址栏,但不会导致页面切换到新视图。

如何让它成功切换到该函数内的 /testimonials 页面?

提前致谢!!!

    if (isMobile === null) {
      setMobileOpen(false);
      setContactModal(!contactModal);
    } else if (isMobile !== null) {
      setMobileOpen(false);
      hist.push('/testimonials')
    }
  };```

标签: redirectreact-router

解决方案


像这样使用 history.push 和 history.go 让它工作

if (isMobile === null) {
      setMobileOpen(false);
      setContactModal(!contactModal);
    } else if (isMobile !== null) {
      setMobileOpen(false);
      hist.push('/testimonials')
      hist.go()
    }
  };

推荐阅读