【问题标题】:Browser History not working when going back in react-router-dom返回 react-router-dom 时浏览器历史记录不起作用
【发布时间】:2019-12-15 23:23:45
【问题描述】:

我们正在使用带有 Razor 视图(纯后端堆栈)的 dotnet 编写的项目。我们计划使用react-router-dom 将每个视图移动到React,以处理客户端和服务器中的路由。

我们的想法是逐页移动,而不是大爆炸,因为该项目已经在生产中。

客户端路由器

import { Router } from 'react-router-dom'
import { createBrowserHistory, History } from 'history'

const history: History = createBrowserHistory({ basename: baseUrl })

<Router history={history}>
  <Switch>
      <Route path="/example" component={Example} />
      ...
   </Switch>
</Router>

服务器路由器

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

<StaticRouter
 basename={basename}
 context={routerContext}
 location={params.location.path}
>
   <Switch>
      <Route path="/example" component={Example} />
      ...
   </Switch>
</StaticRouter>

问题

当我从 /example(在 react 路由器中)导航到 /(在 .net 路由器中)然后我尝试返回 /example 时,似乎没有过渡到 react 路由器并且浏览器历史记录保留在/

【问题讨论】:

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

为了让客户端路由器同时使用客户端导航和直接导航(如浏览器书签、共享链接和 seo),您需要在服务器中配置后备以提供 index.html(女巫将管理客户端路由)

这是因为浏览器不知道你的应用程序的哪一部分是路由管理的。

如果静态文件由静态服务器管理(或者如果您使用反向代理) 比如nginx需要用到try_files,比如https://stackoverflow.com/a/35039350

如果您的静态文件由 .net 应用程序管理,您可能需要配置默认路由,例如 https://stackoverflow.com/a/24564360

在迁移过程中,新的 uri 将按如下方式解析:

  1. 服务器端路由
  2. 回退到客户端路由

应用程序内部的Href会这样解析:

  1. 客户端路由
  2. 回退到服务器端路由。

【讨论】:

  • 这看起来像是您将要做的事情,但我意识到将网站路由的某些部分放在客户端而将其他部分放在服务器上会很奇怪,正如乔纳森在他的帖子中所说的那样。感谢您的帮助。
【解决方案2】:

您可以将每个 .Net 路由添加到您的 React 路由器配置中,该配置在登陆时重新加载 - 类似于:

<Route path="/my-dot-net-page" component={ReloadComp} />

ReloadComp 看起来像这样:

const ReloadComp: React.FC<RouteComponentProps> = props => (window.location.href = props.location.pathname);

当登陆这些路由时,这将导致重新加载,它应该让您的 .Net 网络服务器处理该路由。


另外,我认为在将整个项目转移到 React 之前,可能值得推迟使用 react-router。

你现在想从中得到什么?

如果您在没有完全重新加载的情况下进行导航,它将无法在 React 页面和您的 .Net 页面之间工作 - 需要重新加载。

一旦所有视图都在 React 中,对 react-router 的更改会更简单

【讨论】:

  • 这看起来有点像黑客,正如你所说,在客户端和服务器中拥有部分网站路由会很奇怪。谢谢你让我思考这个问题。
猜你喜欢
  • 2017-08-17
  • 2018-12-26
  • 2018-07-20
  • 2017-01-11
  • 1970-01-01
  • 2018-10-15
  • 2017-12-29
  • 2016-06-28
  • 2015-06-14
相关资源
最近更新 更多