[版权声明] 本站内容采用 知识共享署名-非商业性使用-相同方式共享 3.0 中国大陆 (CC BY-NC-SA 3.0 CN) 进行许可。
部分内容和资源来自网络,纯学习研究使用。如有侵犯您的权益,请及时联系我,我将尽快处理。
如转载请注明来自: Broly的博客,本文链接: React.lazy代码分离,按需加载
前几天React官方更新到16.6.0,
React v16.6.0: lazy, memo and contextType
原生提供了代码分离功能:React.lazy
使用方法很简单,配合Suspense使用
1 2 3 4 5 6 7 8 9 10 |
import React, {lazy, Suspense} from 'react'; const OtherComponent = lazy(() => import('./OtherComponent')); function MyComponent() { return ( <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense> ); } |
体验了下非常不错,不用马上加载太多js文件,而是按需异步加载。
需要注意的是,动态import组件的时候,如果直接传变量是会报错的:
1 2 3 4 5 |
Error: Cannot find module './Home/Home' (anonymous function) e:/demo/src/pages lazy groupOptions: {} namespace object:5 This screen is visible only in development. It will not appear if the app crashes in production. Open your browser’s developer console to further inspect this error. |
解决方法是转成字符串再引用变量,如
1 2 3 4 5 6 |
var path = 'path/to/file.js' require(path) // 报错: Cannot find module "." require('path/to/file.js' ) // 不报错 // 解决方法 require(`${path_to_file}`); // 不报错 |