小编典典

在多页面应用程序中使用React

reactjs

我一直在玩React,到目前为止,我真的很喜欢它。我正在使用NodeJS构建一个应用程序,并希望将React用于整个应用程序中的某些交互式组件。我不想使它成为单页应用程序。

我尚未在网上找到任何可以回答以下问题的信息:

如何在多页面应用程序中分解或捆绑我的React组件?

目前,即使我可能永远不会在应用程序的某些部分中加载它们,我的所有组件也都在一个文件中。

到目前为止,我正在尝试使用条件语句通过搜索React将在其中渲染的容器的ID来渲染组件。我不确定100%的最佳实践是什么。看起来像这样。

if(document.getElementById('a-compenent-in-page-1')) {
    React.render(
        <AnimalBox url="/api/birds" />,
        document.getElementById('a-compenent-in-page-1')
    );
}

if(document.getElementById('a-compenent-in-page-2')) {
    React.render(
        <AnimalBox url="/api/cats" />,
        document.getElementById('a-compenent-in-page-2')
    );
}

if(document.getElementById('a-compenent-in-page-3')) {
    React.render(
        <AnimalSearchBox url="/api/search/:term" />,
        document.getElementById('a-compenent-in-page-3')
    );
}

我仍在阅读文档,还没有找到多页应用程序所需的内容。

提前致谢。


阅读 244

收藏
2020-07-22

共1个答案

小编典典

目前,我正在做类似的事情。

该应用程序不是完整的React App,我使用React进行动态处理,例如aututark的CommentBox。并且可以包含在具有特殊参数的任何点。

但是,我所有的子应用程序都已加载并包含在一个文件中all.js,因此浏览器可以跨页面对其进行缓存。

当我需要将应用程序包含在SSR模板中时,我只需要包含DIV,其类为“ __react-root”和一个特殊ID(要呈现的React App的名称)

逻辑非常简单:

import CommentBox from './apps/CommentBox';
import OtherApp from './apps/OtherApp';

const APPS = {
  CommentBox,
  OtherApp
};

function renderAppInElement(el) {
  var App = APPS[el.id];
  if (!App) return;

  // get props from elements data attribute, like the post_id
  const props = Object.assign({}, el.dataset);

  ReactDOM.render(<App {...props} />, el);
}

document
  .querySelectorAll('.__react-root')
  .forEach(renderAppInElement)

<div>Some Article</div>
<div id="CommentBox" data-post_id="10" class="__react-root"></div>

<script src="/all.js"></script>

编辑

由于webpack完全支持代码拆分和LazyLoading,因此我认为有必要提供一个示例,其中您无需将所有应用程序打包到一个捆绑包中,而是将它们拆分并按需加载。

import React from 'react';
import ReactDOM from 'react-dom';

const apps = {
  'One': () => import('./One'),
  'Two': () => import('./Two'),
}

const renderAppInElement = (el) => {
  if (apps[el.id])  {
    apps[el.id]().then((App) => {
      ReactDOM.render(<App {...el.dataset} />, el);
    });
  }
}
2020-07-22