0

我制作了一个LoaderPage看起来像这样的组件

import theme from "../../assets/styles/globalStyles"
import Loader from "react-loader-spinner"
import React from "react"
import styled from "styled-components"

const Background = styled.div`
    display: "flex",
    align-items: "center",
    justify-content: "center",
    height: "100vh",
    background-color: ${theme.secondary}
`

export default function LoaderPage() {
    return (
        <Background>
            <Loader type="TailSpin" color={theme.primary} height={100} width={100} />
        </Background>
    )
}

我试图将它作为我的路由器组件中的 Suspense 的后备组件,但LoaderPage在任何其他延迟加载的组件加载之前该组件不会显示

import React = require("react")
import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom"
const LoaderPage = import("../../pages/LoaderPage")
const LoginPage = React.lazy(() => import("../../pages/LoginPage"))

import PrivateRoute from "../Router/privateRoute"

export default function SNRoutes(): any {
    return (
        <Router>
            <React.Suspense fallback={LoaderPage}>
                <Switch>
                    <PrivateRoute exact path="/" component={LoginPage} />
                    <Route exact path="/login" component={LoginPage} />
                    <Redirect from="*" to="/" />
                </Switch>
            </React.Suspense>
        </Router>
    )
}

当我复制粘贴 LoaderPage组件并将其保存在我的路由器组件中而不是导入它时,它可以工作。

请帮忙。

4

1 回答 1

0

const LoaderPage = import("../../pages/LoaderPage")是一个返回 Promise 的动态导入。实际LoaderPage可以通过以下方式访问:

let LoaderPage = null;
const LoaderPagePromise = import("../../pages/LoaderPage");
LoaderPagePromise.then(module => LoaderPage = module.default);

这不会像预期的那样工作<Suspense fallback={LoaderPage}>

您应该改用此导入:

import LoaderPage from "../../pages/LoaderPage";
于 2020-08-03T20:39:37.873 回答