导入后备组件时 React Suspense 不起作用

React Suspense not working when fallback component is imported

我制作了一个 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 组件并将其保存在我的 Router 组件中而不是导入它时,它仍然有效。

请帮忙。

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

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

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

一起工作

您应该改用此导入:

import LoaderPage from "../../pages/LoaderPage";