河南自助建站建设代理,酷万网站建设,建设网站费用如何入账,wordpress个性标签lazy内置方法 Suspense内置组件 lazy是React提供的懒#xff08;动态#xff09;加载组件的方法#xff0c;React.lazy() 能减少打包体积、延迟加载首屏不需要渲染的组件 依赖内置组件Suspense#xff1a;给lazy加上loading指示器组件的一个容器组件 Suspense目前只和la…lazy内置方法 Suspense内置组件 lazy是React提供的懒动态加载组件的方法React.lazy() 能减少打包体积、延迟加载首屏不需要渲染的组件 依赖内置组件Suspense给lazy加上loading指示器组件的一个容器组件 Suspense目前只和lazy配合实现组件等待加载指示器的功能 React.lazy 接受一个函数这个函数需要动态调用 import()。它必须返回一个 Promise该 Promise 需要 resolve 一个 default export 的 React 组件。所以要用类返回render而不是函数 index.jsx
import Loading from ./loading
const MyMain React.lazy(() import(./main.jsx))
function App() {return (div{/* 注意 fallback这里是组件 */}React.Suspense fallback{Loading /}MyMain //React.Suspense/div)
}ReactDOM.render(App /,document.getElementById(app)
)main.jsx
// export function Main() {
// return (
// div
// 显示内容
// /div
// )
// }
// React.lazy 接受一个函数这个函数需要动态调用 import()。
// 它必须返回一个 Promise该 Promise 需要 resolve 一个 default export 的 React 组件。
export default class Main extends React.Component {render() {return (div显示内容/div)}
}Loading.jsx
export default function Loading() {return (divh1Loading.../h1h1Loading.../h1h1Loading.../h1/div)
}路由懒加载
yarn add react-router react-router-dom本地调试时path和文件名同名会变成访问文件index.jsx
import Loading from ./loading
import React, { lazy, Suspense } from react
import { BrowserRouter } from react-router-dom
import { Switch, Route } from react-router
const MyMain lazy(() import(./main.jsx))
function App() {return (div{/* 注意 fallback这里是组件 */}Suspense fallback{Loading /}divMyMain /SwitchRoute path/mypage1 component{lazy(() import(./page1.jsx))} /Route path/mypage2 component{lazy(() import(./page2.jsx))} //Switch/div/Suspense/div)
}// 路由懒加载
ReactDOM.render(React.StrictModeBrowserRouterApp //BrowserRouter/React.StrictMode,document.getElementById(app)
);