如何使用 React/Next js 站点的 useEffect hook 延迟加载映射组件

我在我的Next js网站的索引页面上放置了一个Google Maps API组件,但它将负载减慢了一个疯狂的数量(大约500毫秒)。


有没有办法让组件延迟到使用useEffect钩子或以另一种简洁的方式加载页面之后?


我想提高网站的加载速度(和性能分数)。


export default function Home() {

  return (


    <div className={styles.main}>

      <Layout>

        <main className={styles.content}> 


          **<div className={styles.mapContainer}>

            <Map  className={styles.map}/>**


          </div>

        </main>

      </Layout>

    </div>


  )

}


www说
浏览 232回答 1
1回答

拉风的咖菲猫

接下来.js提供了一个帮助程序,该帮助程序仅在组件呈现到页面时加载该组件。dynamichttps://nextjs.org/docs/advanced-features/dynamic-importimport dynamic from 'next/dynamic'const Map = dynamic(() => import('components/MapOrWhatever'));export default function Home() {&nbsp; return (&nbsp; &nbsp; <div className={styles.main}>&nbsp; &nbsp; &nbsp; <Layout>&nbsp; &nbsp; &nbsp; &nbsp; <main className={styles.content}>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className={styles.mapContainer}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Map&nbsp; className={styles.map}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </main>&nbsp; &nbsp; &nbsp; </Layout>&nbsp; &nbsp; </div>&nbsp; )}您还可以将函数的选项指定为第二个参数:dynamicconst Map = dynamic(() => import('components/MapOrWhatever'), {&nbsp; &nbsp; ssr: false, // do not render this on the server side render&nbsp; &nbsp; loading: () => <div>Loading Map...</div>, // placeholder component});如果要将组件的渲染延迟(并因此加载)到特定时间,那么是的,您可以使用效果或其他挂钩来切换地图渲染。例如:export default function Home() {&nbsp; const [showMap, setShowMap] = React.useState(false);&nbsp; React.useEffect(() => {&nbsp; &nbsp; // Set the map to load 2 seconds after first render&nbsp; &nbsp; const timeOut = setTimeout(() => setShowMap(true), 2000);&nbsp; &nbsp; return () => clearTimeout(timeOut);&nbsp; }, []);&nbsp; // <Map> will only load when showMap is true&nbsp; return (&nbsp; &nbsp; <div className={styles.main}>&nbsp; &nbsp; &nbsp; <Layout>&nbsp; &nbsp; &nbsp; &nbsp; <main className={styles.content}>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {showMap && <div className={styles.mapContainer}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Map&nbsp; className={styles.map}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>}&nbsp; &nbsp; &nbsp; &nbsp; </main>&nbsp; &nbsp; &nbsp; </Layout>&nbsp; &nbsp; </div>&nbsp; )}在实践中,最好动态加载隐藏在某种交互背后的组件,例如更改应用程序中的选项卡以加载新路线,或单击“查看地图”按钮。把它放在后面并不是很有成效,你只是人为地任意延迟组件的加载,而没有真正考虑过。但是,我将其作为示例包含在内,以展示动态组件如何仅在它们应该呈现时才加载。setTimeout
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript