如何在React.js中动态加载模块
在React JS中静态加载模块是很麻烦的,因为它会事先加载模块,即使没有被呈现。有些组件只有在用户交互时才会被渲染,所以在这种情况下,它可能导致更多的资源消耗。当您静态导入模块时,您加载的数据比实际需要的数据要多,这可能导致初始页面加载速度较慢。为了解决这个问题,我们可以动态导入模块。接下来,我们将了解如何实现这一点。
先决条件
- React JS
- React JS类组件
- React JS惰性加载
让我们逐步了解使用。
创建React应用程序的步骤
步骤1: 使用create-react-app构建一个React项目
npm create-react-app <project_name>
步骤2: 移动到项目目录
cd <project_name>
项目结构
使用静态加载组件
示例: 这个示例演示了在ReactJS中静态加载资源的方法。这个组件显示了文本,它是从另一个文件静态导入到主文件中的。它在之前就被加载了。
// Filename - index.js
import React from 'react';
import * as ReactDom from 'react-dom';
import App from './app'
const Btn = () => {
const [disp, setDisp] = React.useState(true);
return (disp) ? (<button onClick={() =>
setDisp(false)}>Click Me</button>) : <App />
}
ReactDom.render(<Btn />, document.getElementById('root'));
// Filename - App.js
import React from "react";
import ReactDom from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<p>
The Content is loaded on GeeksforGeeks....
</p>
);
}
}
export default App;
运行应用程序的步骤: 在项目目录中,在终端中使用以下命令。
npm start
输出: 这个输出会在浏览器中显示,地址是 http://localhost:3000/
解释: 在上面的示例中,0.chunk.js在应用程序加载时立即加载。这里的模块在编译时导入。
使用React.lazy()动态加载模块
为了动态导入模块,ReactJS支持 React.lazy() 方法。该方法接受一个函数作为参数,并将组件呈现为常规组件,该函数必须调用返回Promise的import()。这与一起使用,因为它允许我们在等待模块加载时显示后备内容。
示例: 此示例在单击按钮时延迟加载应用程序组件以实现动态加载。
// Filename - App.js
import React from 'react';
import * as ReactDom from 'react-dom';
const Component = React.lazy(() => import('./app'))
const Btn = () => {
const [disp, setDisp] = React.useState(true);
return (disp) ? (<button onClick={() =>
setDisp(false)}>Click Me</button>) :
(<React.Suspense fallback={<div>Loading...</div>}>
<Component />
</React.Suspense>)
}
ReactDom.render(<Btn />, document.getElementById('root'));
import React from "react";
class Text extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<p>
The Content is loaded on GeeksforGeeks....
</p>
);
}
}
export default Text;
运行应用的步骤: 在项目目录的终端中使用以下命令。
npm start
输出: 这个输出将在浏览器中在 http://localhost:3000/ 上可见 。