React很容易实现延迟加载。你需要做的就是使用React.lazy
包动态导入语句import()
Counter.js文件的加载在App.js
中延迟加载此counter
// Counter.js import { useState } from 'React' const Counter = () => { const [count, setCount] = useState(''); const increment = () => setCount(count => count + 1); const decrement = () => setCount(count => count - 1); return ( <div> <button onClick={decrement}> - <button> <span> {count} <span> <button onClick={increment}> + <button> </div> ); };
在App.js
中延迟加载此counter
// App.js import { lazy } from 'React' const Counter = lazy(() => import('./Counter')); const App = () => { return ( <div> <Suspense fallback={<Loader />}> <Counter /> </Suspense> </div> ); };
Counter
仅在需要时才会延迟加载,并且在加载时显示Loader
组件
2. 自定义钩子
useWindowSize
钩子来解决问题import { useState, useEffect } from 'react' function useWindowSize() { const [windowSize, setWindowSize] = useState({ width: 0, height: 0, }) useEffect(() => { const handler = () => { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }) } handler() window.addEventListener('resize', handler) // Remove event listener on cleanup return () => { window.removeEventListener('resize', handler) } }, []) return windowSize }
HOC是React用于重用组件逻辑(组件的重组)的高级技术,它允许你接受组件并返回包含HOC的功能或数据的新组件
withRouter()
或connect()
是一些常见HOC示例
让我们来创建withLayout
HOC,它接受Element并自动添加Navbar、Sidebar和Footer
withLayout函数
const withLayout = (Element) => { return (props) => ( <> <Navbar /> <Sidebar/> <Element {...props} /> <Footer /> </> ); }
使用HOC
const Home = () => { return ( <h1> I am Home! </h1> ) } export default withLayout(Home)