gpt4 book ai didi

reactjs - 如何将多个组件导入为单个组件并在延迟加载中使用它们

转载 作者:行者123 更新时间:2023-12-04 04:12:45 25 4
gpt4 key购买 nike

我有一个条件,我有 3 个组件

A.js B.js C.js

旧代码

routes.js

const A = lazy(() => import("../test/A")); 
const B = lazy(() => import("../test/B"));
const C = lazy(() => import("../test/C"));


<Route
path="/test"
render={({ match: { url } }) => (
<Switch>
<Route exact path={`${url}/a-test`} component={A} />
<Route exact path={`${url}/b-test`} component={B} />
<Route exact path={`${url}/c-test`} component={C} />
</Switch>
)}
/>

我想要实现的目标

By the above code we can conclude that every time the separate builds for A, B, C will get download due to lazy load, but I want to achieve a functionality where I can download all 3 of them altogether, i.e. When a download a single component using that only I can download all three of them as a single separate build

我尝试过的 - 新代码

combine_module.js

import A from "./A";
import B from "./B";
import C from "./C";


const test = {A, B, C};

export default test;

routes.js

const Test = lazy(() => import("../test/combine_module")); 

<Route
path="/test"
render={({ match: { url } }) => (
<Switch>
<Route exact path={`${url}/a-test`} component={Test.A} />
<Route exact path={`${url}/b-test`} component={Test.B} />
<Route exact path={`${url}/c-test`} component={Test.C} />
</Switch>
)}
/>

代码

Full code link

我的问题

我不知道这种方法是对是错,因为我在控制台中没有收到任何错误或与此相关的任何警告,但是看到空白屏幕看不到输出,所以请任何人告诉如何使这件事正确并实现所需的功能。

最佳答案

根据React.lazy文档:

React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.

所以 React.lazy 的结果不是一个模块,而是一个 Suspense 可以使用的特殊对象。

可以使用 WebPack 的 dynamic import 延迟加载常用模块.这有一个棘手的部分,因为可以在渲染组件后加载模块。所以我们需要做两件事:
1) 确保组件在加载模块时不呈现 undefined
2) 加载模块时更新组件

更新非常简单,我们可以制作一个钩子(Hook),将模块设置为加载状态

function useDynamicModule(path) {
const [module, setModule] = useState({});
const [error, setError] = useState();
useEffect(() => {
import(path).then(setModule, setError);
}, []);
return error ? { $error: error } : module.default
}

用法:

export default function App() {
const Test = useDynamicModule("./CombineModule");

if (!Test) return null;
if (Test.$error) return "Error";
return (
<Router history={history}>
// ...
</Router>
);
}

Playground

关于reactjs - 如何将多个组件导入为单个组件并在延迟加载中使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61439315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com