我们正在一个用dotnet编写的项目中使用Razor视图(纯后端堆栈)。我们计划使用React
将每个视图移动到react-router-dom
来处理客户端和服务器中的路由。
我们要记住的是,不要逐页移动,因为该项目已经在生产中了。
当我设置react-router-dom
时,似乎每个页面都在客户端上处理,并且如果路由不在Router
处理的路由之内,则不会重新加载整个页面。
客户端路由器
import { Router } from 'react-router-dom'
import { createBrowserHistory, History } from 'history'
const history: History = createBrowserHistory({ basename: baseUrl })
<Router history={history}>
...(routes and page layout)
</Router>
服务器路由器
<StaticRouter
basename={basename}
context={routerContext}
location={params.location.path}
>
...(routes and page layout)
</StaticRouter>
有什么方法可以使路由器以这种方式工作:
如果路由在
react-router-dom
处理的路由之内,则进行客户端转换如果路由器不在
react-router-dom
处理的路由器之内(这意味着仍由dotnet后端处理),请重新加载整个页面。如果您需要更多信息,请与我们联系。
先感谢您。
最佳答案
您需要在NoMatch
的末尾添加*路线的Router
组件
<Route component={NoMatch} />
并定义您的
NoMatch
组件,如下所示function NoMatch() {
window.location.reload();
return null;
}
另外,您的路线应在
<Switch>
内,因为否则NoMatch
将与您的路线一样执行,这将导致无限循环。请参阅文档以获取更多详细信息:https://reacttraining.com/react-router/web/api/Switch