我正在使用 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 播放器和照片组件也会被加载 - 只是没有使用。
那么......有没有办法根据数据渲染组件,然后导致正确的代码拆分?
太感谢了!