MPA 中的 React 上下文(不同应用程序的一个上下文)

React context in MPA (one context for different apps)

我在一个页面上渲染了几个反应“片段”

ReactDOM.render(<MainNavSearchApp />, document.getElementById('main-nav-search-app'));
ReactDOM.render(<NavSearchBrandsApp />, document.getElementById('main-nav-search-brands-app'));

并想为他们使用一个上下文

class MainNavSearchApp extends React.Component {
    render() {
        return (
            <div>
                <NavSearchContextProvider>
                    <MainNavSearch />
                </NavSearchContextProvider>
            </div>
        );
    }
}
export default MainNavSearchApp; 

class NavSearchBrandsApp extends React.Component {
    render() {
        return (
            <div>
                <NavSearchContextProvider>
                    <NavSearchBrands />
                </NavSearchContextProvider>
            </div>
        );
    }
}

export default NavSearchBrandsApp; 

但是如果我更新其中一个应用程序的上下文,它不会在另一个应用程序中更新。据我了解,React 创建了两个“克隆”独立上下文。多个实例可以使用相同的上下文吗?

是的,你可以,因为 data in React flows down,它们必须有一个共同的父级才能共享相同的上下文数据。

This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.

因此,公共父组件应该使用ReactDOM.createPortal,并渲染提供者,而其他组件将是他的子组件。

<body>
    <div id="root"></div>
    <div id="app1"></div>
    <div id="app2"></div>
</body>
// Common parent - MUST
function Root() {
  return (
    <Context.Provider value={42}>
      {ReactDOM.createPortal(<App1 />, document.getElementById("app1"))}
      {ReactDOM.createPortal(<App2 />, document.getElementById("app2"))}
    </Context.Provider>
  );
}

// MainNavSearchApp
function App1() {
  const val = React.useContext(Context);
  return <>App1: {val}</>;
}

// NavSearchBrandsApp
function App2() {
  const val = React.useContext(Context);
  return <>App2: {val}</>;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Root />, rootElement);