React 源碼閱讀-6
lazy
React.lazy
函數能讓你像渲染常規組件一樣處理動態引入(的組件)。
React.lazy
接受一個函數,這個函數需要動態調用 import()
。它必須返回一個 Promise
,該 Promise
需要 resolve
一個 defalut export
的 React
組件。
React.lazy並不適合SSR
import type {LazyComponent, Thenable} from 'shared/ReactLazyComponent';
import {REACT_LAZY_TYPE} from 'shared/ReactSymbols';
import warning from 'shared/warning';
export function lazy<T, R>(ctor: () => Thenable<T, R>): LazyComponent<T> {
let lazyType = {
$$typeof: REACT_LAZY_TYPE,
_ctor: ctor,
// React uses these fields to store the result.
_status: -1,
_result: null,
};
if (__DEV__) {
// In production, this would just set it on the object.
let defaultProps;
let propTypes;
Object.defineProperties(lazyType, {
defaultProps: {
configurable: true,
get() {
return defaultProps;
},
set(newDefaultProps) {
warning(
false,
'React.lazy(...): It is not supported to assign `defaultProps` to ' +
'a lazy component import. Either specify them where the component ' +
'is defined, or create a wrapping component around it.',
);
defaultProps = newDefaultProps;
// Match production behavior more closely:
Object.defineProperty(lazyType, 'defaultProps', {
enumerable: true,
});
},
},
propTypes: {
configurable: true,
get() {
return propTypes;
},
set(newPropTypes) {
warning(
false,
'React.lazy(...): It is not supported to assign `propTypes` to ' +
'a lazy component import. Either specify them where the component ' +
'is defined, or create a wrapping component around it.',
);
propTypes = newPropTypes;
// Match production behavior more closely:
Object.defineProperty(lazyType, 'propTypes', {
enumerable: true,
});
},
},
});
}
return lazyType;
}
使用前
import OtherComponent from './OtherComponent';
使用後
const OtherComponent = React.lazy(() => import('./OtherComponent'));
在組件首次渲染時,自動導入包含 OtherComponent
組件的包。
路由分割代碼
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
</Switch>
</Suspense>
</Router>
);
https://juejin.im/post/5c7d4a...
https://zh-hans.reactjs.org/d...