我可以在函数中使用 React.lazy 吗?
Can I use React.lazy inside a function?
我想知道是否可以以通用方式(例如在函数中)延迟加载组件。
示例:
function renderLazyComponent() {
if (/* condition */) {
return React.lazy(async () => {
const module = await import('mathLibraryForExample');
return { default: (props) => <p>{module.multiply(1, 2)}</p> }
})
} else {
return React.lazy(async () => {
const module = await import('mathLibraryForExample');
return { default: (props) => <p>{module.division(1, 3)}</p> }
})
}*/
}
function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
{ renderLazyComponent() }
</Suspense>
);
}
因为我总是得到这个错误:```Objects are not valid as a React child (found: object with keys {$$typeof, _ctor, _status, _result})。如果你打算渲染一个子集合,请改用数组。```
我想路径“./components/”是您的组件的位置。
第一种方法:
const FirstComponent = lazy(() => import('./components/first'));
const SecondComponent = lazy(() => import('./components/second'));
function App() {
return (
<>
<Suspense fallback={<div>Loading</div>}>
{ condition ? <FirstComponent /> : <SecondComponent /> }
</Suspense>
</>
);
}
第二种方法:
function renderLazyComponent(component) {
return lazy(() => import('./components/' + component));
}
function App() {
return (
<>
<Suspense fallback={<div>Loading</div>}>
{ renderLazyComponent('first') }
{ renderLazyComponent('second') }
</Suspense>
</>
);
}
我想知道是否可以以通用方式(例如在函数中)延迟加载组件。
示例:
function renderLazyComponent() {
if (/* condition */) {
return React.lazy(async () => {
const module = await import('mathLibraryForExample');
return { default: (props) => <p>{module.multiply(1, 2)}</p> }
})
} else {
return React.lazy(async () => {
const module = await import('mathLibraryForExample');
return { default: (props) => <p>{module.division(1, 3)}</p> }
})
}*/
}
function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
{ renderLazyComponent() }
</Suspense>
);
}
我想路径“./components/”是您的组件的位置。
第一种方法:
const FirstComponent = lazy(() => import('./components/first'));
const SecondComponent = lazy(() => import('./components/second'));
function App() {
return (
<>
<Suspense fallback={<div>Loading</div>}>
{ condition ? <FirstComponent /> : <SecondComponent /> }
</Suspense>
</>
);
}
第二种方法:
function renderLazyComponent(component) {
return lazy(() => import('./components/' + component));
}
function App() {
return (
<>
<Suspense fallback={<div>Loading</div>}>
{ renderLazyComponent('first') }
{ renderLazyComponent('second') }
</Suspense>
</>
);
}