首页 > 解决方案 > React:在 App.tsx 中为已解决的组件做上述事情吗?

问题描述

我有一个侧边栏和主要类型的布局。我想在主线程上放置一个微调器,直到 API 请求完成,或者在componentDidMount完成时更好

在我的所有页面中,我似乎都将这个 commong 代码放入了 render()

常用代码:

if (!this.state.finishedApiRequests) {
    return (<div className="flex justify-center items-center mt-5 mb-5">
                <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-gray-900"></div>
            </div>)
}

有没有更好的办法?我确实有 App.tsx,这是我认为最适合的地方,但我不确定如何从路由组件中获取已解析的组件,然后检查所述元素的状态finishedApiRequests

这是我的应用程序组件:

function App() {
    return (
        <div>
            <Router>
                <div>
                    <Switch>
                        <GuestRoute exact path="/" component={Login} />
                        <ProtectedRoute exact path="/home" component={Home} />
                        <ProtectedRoute exact path="/alerts" component={Alerts} />
                        <ProtectedRoute exact path="/profiles" component={Profiles} />
                        <ProtectedRoute exact path="/profiles/:id" component={Profile} />
                        <ProtectedRoute exact path="/queue-items" component={QueueItems} />
                        <ProtectedRoute exact path="/accounts" component={Accounts} />
                        <ProtectedRoute exact path="/workers" component={Workers} />
                        <ProtectedRoute exact path="/collections" component={Collections} />
                        <ProtectedRoute exact path="/collections/:id" component={Collection} />
                        <ProtectedRoute exact path="/livestream" component={Livestream} />
                        <ProtectedRoute exact path="/utilities" component={Utilities} />
                        <ProtectedRoute exact path="/utilities/pending-queue-items" component={PendingQueueItems} />
                        <ProtectedRoute exact path="/utilities/profile-to-collection" component={ProfileToCollection} />
                        <Route path='*' exact={true} component={PageNotFound} />
                    </Switch>
                </div>
            </Router>
        </div>
    );
}

受保护的路由组件:

export default function ProtectedRoute({...routeProps}: RouteProps) {
    return localStorage.getItem('access_token') ?
        <div className="flex">
            <aside className="h-screen sticky top-0">
                <Sidebar />
            </aside>
            <main className="p-5 w-full">
                <Route {...routeProps} />
            </main>
        </div> :
        <Redirect to="/" />;
};

标签: reactjstypescript

解决方案


推荐阅读