reactjs - How to use multiple react suspense fallbacks with reach router?
问题描述
I'm using "@reach/router": "^1.2.1"
and in my App.js
file I've got a fallback component to show while my routes are loading:
<React.Suspense fallback={<MainLandingPageLoadingScreen />}>
<Router>
<MainLandingPage path="/" />
<AnotherLandingPage path="/coolbeans" />
<NotFound default />
</Router>
</React.Suspense>
But depending on the route, I want to use a different loading component as the fallback, so something like:
<Router>
<React.Suspense fallback={<AnotherLandingPageLoadingScreen />}>
<MainLandingPage path="/" />
<NotFound default />
</React.Suspense>
<React.Suspense fallback={<AnotherLandingPageLoadingScreen />}>
<AnotherLandingPage path="/coolbeans" />
</React.Suspense>
</Router>
This won't work because Router needs to be wrapped around Suspense, instead of this way around. But if I split it like below then the second Router list doesn't get picked up and the route is a 404:
<React.Suspense fallback={<MainLandingPageLoadingScreen />}>
<Router>
<MainLandingPage path="/" />
<NotFound default />
</Router>
</React.Suspense>
<React.Suspense fallback={<AnotherLandingPageLoadingScreen />}>
<Router>
<AnotherLandingPage path="/coolbeans" />
</Router>
</React.Suspense>
What is the correct way to provide a fallback component on a routing level?
解决方案
嘿,所以我在这个场景中使用了 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() 钩子,它可以为你获取路径名,看起来 Reach 路由器也有定位功能。
您的函数将尝试匹配路径名,并根据您导航到的路径返回适当的加载组件:
const showAppropriateLoadingComponent = (pathname: string) => {
switch (pathname) {
case '/':
return <LoadingComponent1 />;
break;
case '/coolbeans':
return <LoadingComponent2 />;
break;
case default:
return <DefaultLoadingComponent />
break;
}
}
然后在您的实际路由器文件中,您只需调用 suspense fallback 中的函数并将路径名作为参数传递。
const Router = () => {
const { pathname } = useLocation();
<Router>
<React.Suspense fallback={showAppropriateLoadingComponent(pathname)}>
<MainLandingPage path="/" />
<NotFound default />
<AnotherLandingPage path="/coolbeans" />
</React.Suspense>
</Router>
}
推荐阅读
- python - 通过 API 从 Delta Exchange 获取数据
- solr - CKAN 中的数据集格式过滤
- sql - 在范围内添加日期
- java - java.lang.IllegalStateException:充气机已关闭
- swift - 如何快速使 Collectionview 单元格彼此靠近?
- firebase - Firebase 托管 - 尝试在工作区中绑定“/%PUBLIC_URL%/manifest.json”失败,因为此 URI 格式错误
- html - HTML 网站导航不再起作用
- kubernetes - 在 GKE 的 HPA 中扩展时出错:apiserver 无法写入 JSON 响应:http2:流已关闭
- python - 在 TensorFlow 不规则张量上使用 len()
- python - sklearn.preprocessing.MinMaxScalar 中“inverse_transform”函数的奇怪行为