我正在使用 "@reach/router": "^1.2.1"
并且在我的 App.js
文件中我有一个后备组件来显示当我的路线正在加载时:
<React.Suspense fallback={<MainLandingPageLoadingScreen />}>
<Router>
<MainLandingPage path="/" />
<AnotherLandingPage path="/coolbeans" />
<NotFound default />
</Router>
</React.Suspense>
但是根据路线,我想使用不同的加载组件作为回退,所以像这样:
<Router>
<React.Suspense fallback={<AnotherLandingPageLoadingScreen />}>
<MainLandingPage path="/" />
<NotFound default />
</React.Suspense>
<React.Suspense fallback={<AnotherLandingPageLoadingScreen />}>
<AnotherLandingPage path="/coolbeans" />
</React.Suspense>
</Router>
这行不通,因为 Router 需要包裹在 Suspense 周围,而不是这样。但是如果我像下面那样拆分它,那么第二个路由器列表不会被拾取并且路由是 404:
<React.Suspense fallback={<MainLandingPageLoadingScreen />}>
<Router>
<MainLandingPage path="/" />
<NotFound default />
</Router>
</React.Suspense>
<React.Suspense fallback={<AnotherLandingPageLoadingScreen />}>
<Router>
<AnotherLandingPage path="/coolbeans" />
</Router>
</React.Suspense>
在路由级别提供回退组件的正确方法是什么?
最佳答案
嘿,所以我在这个场景中使用了 React Router 而不是 Reach Router,但我认为同样的想法也适用。
您仍然希望只在所有路由周围包裹 1 个 Suspense 组件:
<Router>
<React.Suspense fallback={// will get to this}>
<MainLandingPage path="/" />
<NotFound default />
<AnotherLandingPage path="/coolbeans" />
</React.Suspense>
</Router>
但是您需要创建一个函数来传递到检查特定组件路径名的回退中。 React 路由器有 useLocation() Hook ,它可以为您获取路径名,看起来 Reach Router 也有定位功能。
您的函数将尝试匹配路径名,并根据您导航到的路径返回适当的加载组件:
const showAppropriateLoadingComponent = (pathname: string) => {
switch (pathname) {
case '/':
return <LoadingComponent1 />;
break;
case '/coolbeans':
return <LoadingComponent2 />;
break;
case default:
return <DefaultLoadingComponent />
break;
}
}
然后在您的实际路由器文件中,您只需调用悬念回退中的函数并将路径名作为参数传递。
const Router = () => {
const { pathname } = useLocation();
<Router>
<React.Suspense fallback={showAppropriateLoadingComponent(pathname)}>
<MainLandingPage path="/" />
<NotFound default />
<AnotherLandingPage path="/coolbeans" />
</React.Suspense>
</Router>
}
关于reactjs - 如何使用到达路由器的多个 react 悬念回退?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56359063/