2

我正在使用 Gatsby 和 Contentful 构建网站,到目前为止效果很好。我的问题是,我不知道如何根据 Contentful 中的数据动态呈现组件。

假设有一个页面内容类型,它作为组件的标题、url 和字段。这些组件可以是 YouTube 播放器、降价文本或照片。目前我正在使用一个自定义组件,它导入所有可用的组件,然后使用 switch 呈现页面的组件。

switch (contentType) {
  case 'billboard':
    return <Billboard key={key} id={key} {...section.fields}/>;
  case 'photos':
    return <Photos key={key} id={key} {...section.fields}/>;
  case 'postGrid':
    return <PostGrid key={key} id={key} {...section.fields}/>;
  case 'splitView':
    return <SplitView key={key} id={key} {...section.fields}/>;
  case 'text':
    return <Text key={key} id={key} {...section.fields}/>;
  case 'tile':
    return <Tile key={key} id={key} {...section.fields}/>;
  default:
    return null;
}

这样做的问题是 Gatsby 将在 webpack 块中包含所有可用的组件,如果有很多组件,这会导致站点崩溃。假设有一个只有文本的页面(例如印记),YouTube 播放器和照片组件也会被加载 - 只是没有使用。

那么......有没有办法根据数据渲染组件,然后导致正确的代码拆分?

太感谢了!

4

2 回答 2

1

我正在考虑另一种方法;在基于 呈现您的组件类型的映射组件中contentType,更清洁,尤其是巨大的性能改进(无需switch每次都强制代码检查语句)。

如果没有看到其余的代码,很难猜出你是如何打印的switch。但是,假设您在data对象中拥有所有数据,那么:

import SwitchComponents from '../../SwitchComponents/SwitchComponents'

 // other code

  return data.map(item => {
    const Switcher = SwitchComponents[item.contentType];
    return (
      <Switcher
        key={item.key} // or something unique
        {...section.fields}
      />
    );
  })

该组件应该具有类似的结构,例如:

import Billboard from './Billboard/Billboard';
import Photos from './Photos/Photos';
import PostGrid from './PostGrid/PostGrid';
import SplitView from './SplitView /SplitView';
import Text from './Text/Text';
import Tile from './Tile/Tile';

const SwitchComponents= {
  billboard : Billboard,
  photos : Photos,
  postGrid : PostGrid,
  splitView : SplitView,
  text : Text,
  tile : Tile  
};

export default SwitchComponents

基本上你是在告诉它应该采取SwitchComponents[item.contentType]的位置SwitchComponents,因为它被映射为一个组件(在 中导入SwitchComponents)并呈现为<Switcher/>将获得一个组件并且会成功。

如果问题中断,我很乐意上传问题,但我希望你能得到我的解决方法。

让我知道它是如何工作的!

于 2020-07-08T15:47:49.963 回答
1

React Loadable对我来说非常出色。这是添加库使包更小的情况之一。

您可能还希望将异步加载推迟到用户滚动到特定元素时,这个库本身不会这样做。您可以轻松地将原始版本与 InteractionObserver 版本 - react-loadable-visibility混合使用。但是,请确保您有处理 CLS(累积布局转换)的好方法,否则 Lighthouse 会抱怨您的网站元素让您的用户感到沮丧。

于 2021-04-06T13:14:58.720 回答