[英]Page reload if react-router-dom doesn't match any route
我们正在使用带有 Razor 视图(纯后端堆栈)的 dotnet 编写一个项目。 我们计划使用react-router-dom
将每个视图移动到React
来处理客户端和服务器中的路由。
我们的想法是一页一页地移动,不要因为项目已经在生产中而大吵大闹。
当我设置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 后端处理),请重新加载整个页面。如果您需要更多信息,请与我们联系。 先感谢您。
您需要在Router
的末尾为 * 路由添加一个NoMatch
组件
<Route component={NoMatch} />
并定义您的NoMatch
组件,如下所示
function NoMatch() {
window.location.reload();
return null;
}
此外,您的路线应该在<Switch>
,否则NoMatch
将与您的路线一样执行,这将导致无限循环。 有关更多详细信息,请参阅文档: https : //reacttraining.com/react-router/web/api/Switch
幸运的是,我们有history
道具可以提供帮助,它提供了一个action
参数,可以指示用户是从另一条路线导航还是直接从当前路线开始。
所以这就是我解决重新加载循环问题的方法:
/**
* Handles Legacy/SSR pages, reloads the page when the location changes
*
* @param {object} props Props
* @param {object} props.location Location object
* @param {object} props.history History object
*/
const LegacyRoute = ( { location, history } ) => {
useEffect( () => {
// Reload the page if the location change ( and not on first load )
if ( history.action === 'PUSH' ) {
window.location.reload();
}
return () => {
// Reload the page if we navigate away to another route
window.location.reload();
}
}, [ location.pathname ] );
return null;
}
然后将路由定义为:
<Route component={ LegacyRoute } />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.