1

我有一个 spa 应用程序,我在其中使用 3 个子应用程序(每个都是微前端)。对于 1 个子应用程序,我正在安装到根 html 并设置为始终处于活动状态。对于其余 2,根据路线,将自己挂载/卸载到根 html 上。对于始终处于活动状态的孩子,我将当前路径作为道具从根传递,以便基于该路径,该孩子中的组件应该呈现(条件渲染)。我面临的问题是,孩子能够从根目录接收道具,但是当路径发生变化时,新路径不会反映到孩子身上,我必须手动重新加载页面才能有条件地在其中渲染这些组件那个儿童应用程序。所以,这里是 root-config.js 文件和 child.js 文件。

**root-config.js**

import { registerApplication, start } from "single-spa";
registerApplication({
  name: "@mrc/app1",
  app: () => System.import("@mrc/app1"),
  activeWhen: ["/app1", (location) => location.pathname.startsWith("/app1")],
});

registerApplication({
  name: "@mrc/app2",
  app: () => System.import("@mrc/app2"),
  activeWhen: ["/app2", (location) => location.pathname.startsWith("/app2")],
});

registerApplication({
  name: "@mrc/app3",
  app: () => System.import("@mrc/app3"),
  activeWhen: ["/"],
  customProps: {
    currentPath: window.location.pathname,
  },
});

start();
**app3.js**

import React from "react";
import Header from "./components/Header/Header";
import LeftPane from "./components/LeftPane/LeftPane";
import NavBody from "./components/NavBody/NavBody";

const App = ({ currentPath }) => {
  return (
    <>
      <Header />
      {typeof window !== "undefined" && currentpath !== "/" ? (
        <LeftPane />
      ) : null}
      {typeof window !== "undefined" && currentPath === "/" ? (
        <NavBody />
      ) : null}
    </>
  );
};

export default App;

目标是 app3 中的 LeftPane 组件不应该只为 path="/" 呈现,而 NavBody 应该只为 path="/" 呈现。我怎样才能做到这一点?

4

1 回答 1

0

我是single-spa. 感谢您指出可能更清楚的文档区域。

从该方法传入的自定义道具registerApplication不是“实时”的,也不会自动更新。幸运的是,您可以通过几种不同的方式来完成您想要完成的工作,以满足您的需求。

选项:

  1. window.location.pathname而不是从registerApplication通话中传下来。直接用在@mrc/app3
  2. 让 app3 使用某种路由器(可能是 react-router)并使用其中的路由

还有其他一些选择,但我认为其中任何一个都可以解决您面临的问题。

single-spa旨在成为微前端之间的顶级路由器。每个微前端通常都有自己的路由。

请参阅此示例以及 single-spa 如何仅处理顶级路由 planets处于活动状态/planets,然后行星应用程序在内部执行路由以使组件在特定路由处处于活动状态。

于 2021-08-03T15:41:45.727 回答