我正在使用code-splitting reactjs的延迟加载概念。但是<Suspense>
似乎不适用于我,因为它没有向我显示后备加载消息并直接在其内部的render上加载代码。
我正在本地开发环境中运行react应用,但未使用其生产版本。下面是我正在使用的代码。
import React,{ lazy, Suspense } from 'react';
class Homepage extends React.Component{
render(){
return(
<div>
<Suspense fallback={<h2>Products are loading...</h2>}>
// products display code
</Suspense>
</div>
);
}
App.js
import React, { lazy, Suspense } from 'react'
import { BrowserRouter, Switch, Route } from 'react-router-dom'
const HomePage = lazy(() => import('./pages/home/HomePage'))
class App extends React.Component {
render() {
return (
<BrowserRouter>
<Switch>
<Suspense fallback={<h2>Loading...</h2>}>
<Route exact path='/' component={HomePage}/>
</Suspense>
</Switch>
</BrowserRouter>
)
}
}
export default App
延迟加载产品组件,setTimeout为0,1000仅用于调试
HomePage.js
import React, { lazy, Suspense } from 'react' const Products = React.lazy(() => { return new Promise(resolve => setTimeout(resolve, 1000)).then( () => import(".../components/products/Products") ); }); export default function HomePage() { return ( <div> <Suspense fallback={<h2>Products are loading...</h2>}> <Products /> </Suspense> </div> ); }