gpt4 book ai didi

javascript - 状态内 react 组件的动态加载

转载 作者:行者123 更新时间:2023-12-03 02:52:00 26 4
gpt4 key购买 nike

我手头有一个非常有趣的问题。

我目前正在开发 headless CMS 的管理界面,我想动态加载组件以查看不同部分的内容。

我知道从 v4 开始使用 React Router 来完成这个任务相当容易,但我不想依靠路由来处理这个问题以保持 URL 尽可能干净。

这是我正在尝试做的事情:

  1. 我想渲染 UI 的基本布局(我在其中加载单击导航链接时的不同子组件)
  2. async componentWillMount() 内我想要这个基本布局的功能import()使用 await import() 表示组件
  3. 理想情况下,这些应该存储到名为 this.state.mainComponents 的属性内的状态。
  4. 然后,我会将组件的名称连同一个函数一起传递给导航组件,该函数将更改父组件中当前显示的组件 state

我尝试了几种不同的方法,但直到现在才成功。

这就是我现在拥有的:

  async componentDidMount() {
const mainComponents = {
Dashboard: await import('../_mainComponents/Dashboard').then(
({ Dashboard }) => {
return Dashboard;
},
),
};

const componentNames = [];

for (let p in mainComponents) {
componentNames.push(p);
}

this.setState({
mainComponents: {
views: mainComponents,
names: componentNames,
},
currentComponent: mainComponents.Dashboard,
currentTitle: 'Dashboard',
});
}

我非常感谢您在这方面能给我的任何帮助。

编辑:

所以根据@Mosè Raguzzini的回答我实现了react-loadable再次尝试将 const 存储在我的状态中,如下所示:

const LoadableDashboard = Loadable({
loader: () => import('../_mainComponents/Dashboard'),
loading: Loading
});

const mainComponents = {
Dashboard: LoadableDashboard
};

在我的构造函数中,我尝试将此对象传递到如下状态:

const componentNames = [];

for (let p in mainComponents) {
componentNames.push(p);
}

this.state = {
mainComponents: {
views: mainComponents,
names: componentNames,
},
currentComponent: null,
currentTitle: null,
loading: false,
};

尝试输出存储在this.state.mainComponents.views内的组件时它不起作用。渲染函数内部的对象。

当使用<Dashboard />时它按预期工作,但这不是我在这里想要完成的目标,因为我不想将每个组件添加到大量 switch ... case 中的渲染函数中.

你们中有人知道我该如何实现这一目标吗?

最佳答案

我找到了问题的解决方案,并希望与所有追随我寻找合适答案的人分享。

这是我所做的:

import Loadable from 'react-loadable';
import Loading from '../_helperComponents/Loading';

// Define the async-loadable components here and store them inside of the mainComponent object
const LoadableDashboard = Loadable({
loader: () => import('../_mainComponents/Dashboard'),
loading: Loading,
});

const LoadableUserOverview = Loadable({
loader: () => import('../_mainComponents/UserOverview'),
loading: Loading,
});

const mainComponents = {
Dashboard: <LoadableDashboard />,
User: <LoadableUserOverview />,
};

我不会将组件存储在我的状态中(这是可能的,但违反了指导方针,因为我通过进一步研究状态发现了这一点):D

有了这个对象,我可以通过在 render() 函数中输出来简单地调用相应的组件,如下所示:

render() {
return (
<div>
{mainComponents[this.state.currentComponent]}
</div>
);
}

我希望我能帮助别人解决这个问题。快乐编码!

关于javascript - 状态内 react 组件的动态加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47811262/

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