简体   繁体   English

如何使用 React Router 5 模拟 window.location?

[英]How to emulate window.location with React Router 5?

I have a react SPA that is served by Laravel.. I want the SPA to be able to go to some pages that are also served by Laravel..我有一个由 Laravel 提供服务的 react SPA。我希望 SPA 能够访问一些也由 Laravel 提供服务的页面。

Update:更新:

As an example... in my coreui-react based app.. I want to allow the user to open the user manual which is built using vuepress.举个例子……在我基于 coreui-react 的应用程序中……我想允许用户打开使用 vuepress 构建的用户手册。 I want to be able to open it in a brand new page and not have it bundled into the SPA.我希望能够在一个全新的页面中打开它,而不是将它捆绑到 SPA 中。 The SPA shows up at https://test.local/ the user manual is at https://test.local/docs SPA 显示在https://test.local/用户手册位于https://test.local/docs

Link to="/docs" flicks me back to the SPA, Link to="//test.local/docs" also as does Link to="/docs" 让我回到 SPA,Link to="//test.local/docs" 也一样

I've also tried placing onClick={() => window.location = window.location.protocol + "//" + window.location.hostname + "/docs"} inside the Link but no change except that it does drop out of the local dev server (port 3000).. but if its in a build - then it still gets caught by the ReactRouter我也试过在链接中放置 onClick={() => window.location = window.location.protocol + "//" + window.location.hostname + "/docs"} 但没有变化,除了它确实下降离开本地开发服务器(端口 3000)...但如果它在构建中 - 那么它仍然会被 ReactRouter 捕获

There is a suggestion that StaticRouter would do it - but all the examples I see refer to server side rendering of content that the SPA will consume, not flicking you out to a server delivered page..有一个建议是 StaticRouter 会这样做 - 但我看到的所有示例都是指 SPA 将使用的内容的服务器端呈现,而不是将您弹到服务器交付的页面。

I'm kinda at my wits end.. my only thought at the moment is to move the SPA from "/" to "/app" and and not handle "/" at all within the SPA with the hope that ReactRouter might let that through我有点不知所措..我目前唯一的想法是将 SPA 从“/”移动到“/app”,并且在 SPA 内根本不处理“/”,希望 ReactRouter 可以允许通过

This seems to be a long term issue in ReactRouter.. but in the past you could brute-force your way out with <a href or window.location - but seems no longer to be the case..这似乎是 ReactRouter 中的一个长期问题.. 但在过去,您可以使用 <a href 或 window.location 强行退出 - 但似乎不再如此..

If I understand correctly, you can use "history":如果我理解正确,您可以使用“历史”:

const history = useHistory();

you have to import useHistory from react-router-dom :你必须从react-router-dom导入useHistory

import { useHistory } from 'react-router-dom'

and then you can use:然后你可以使用:

history.push('/analytics')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM