我们正在开发一个用 dotnet 编写的项目,带有 Razor View (纯后端堆栈)。我们计划使用 react-router-dom
将每个 View 移动到 React
来处理客户端和服务器中的路由。
我们的想法是一页一页地移动,而不是大爆炸,因为该项目已经在生产中。
当我设置react-router-dom
时,看起来每个页面都在客户端上处理,并且如果路由不在Router
的路由内,则不会重新加载整个页面> handle 。
客户端路由器
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
关于javascript - 如果react-router-dom不匹配任何路由,则页面重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57389750/