React.lazy() 和 React.Suspense 可以用來實現組件的懶加載,從而優化移動端的性能。以下是一些在移動端應用中實現懶加載的技巧:
import React, { lazy, Suspense } from 'react';
const MyComponent = lazy(() => import('./MyComponent'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
</div>
);
}
import React, { lazy, Suspense, memo } from 'react';
const MyComponent = lazy(() => import('./MyComponent'));
const MemoizedMyComponent = memo(MyComponent);
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<MemoizedMyComponent />
</Suspense>
</div>
);
}
import React, { useState, useEffect } from 'react';
const MyComponent = lazy(() => import('./MyComponent'));
function App() {
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsVisible(true);
observer.unobserve();
}
});
});
if (isVisible) {
observer.observe(document.querySelector('.lazy-load-container'));
}
return () => {
if (isVisible) {
observer.unobserve(document.querySelector('.lazy-load-container'));
}
};
}, [isVisible]);
return (
<div>
{isVisible && <MyComponent />}
</div>
);
}
import React, { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</Suspense>
</Router>
);
}
import React, { lazy, Suspense } from 'react';
const MyComponent = lazy(() => import(/* webpackChunkName: "my-component" */ './MyComponent'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
</div>
);
}
通過以上技巧,你可以在移動端應用中實現組件的懶加載,從而提高應用的性能和用戶體驗。