如何仅通过JavaScript实现两个single-spa React应用间的切换,以及切换后强制卸载未自动卸载的原应用?
Hey there! Let's tackle your single-spa React questions one by one—super common scenarios when working with microfrontends, so I’ve got you covered.
Single-spa’s built-in navigateToUrl function is exactly what you need here, but you’ll want to make sure your apps are set up with proper routing rules first. Here’s the step-by-step:
- First, when registering your apps (via
registerApplication), define clearactiveWhenconditions tied to URL paths. For example, app A activates when the path starts with/app-a, and app B activates for/app-b. - In your app A code, import
navigateToUrlfrom@single-spa/reactand call it with the target path for app B. This triggers a route change, and single-spa will handle activating app B based on youractiveWhenrules.
Here’s a quick code example for a button in app A that switches to app B:
import { navigateToUrl } from '@single-spa/react'; function SwitchToAppBButton() { const handleSwitch = () => { navigateToUrl('/app-b'); }; return <button onClick={handleSwitch}>跳转到应用B</button>; }
By default, single-spa keeps inactive apps mounted but in an "inactive" state to optimize reload times when switching back. If you need to fully unmount app A when moving to app B, here are two reliable methods:
Method 1: Use single-spa’s unmountApplication API
Single-spa provides the unmountApplication method to manually trigger an app’s unmount lifecycle. You can call it right after navigating to app B:
import { navigateToUrl, unmountApplication } from '@single-spa/react'; const switchAndUnmount = () => { // Navigate to app B first navigateToUrl('/app-b'); // Unmount app A using its registered name (the first parameter in registerApplication) unmountApplication('app-a') .then(() => console.log('应用A已成功卸载')) .catch(err => console.error('卸载应用A时出错:', err)); };
Note: Once unmounted, app A will be re-mounted automatically if the user navigates back to /app-a—this is expected behavior.
Method 2: Auto-unmount on route change (root config level)
If you want app A to unmount automatically whenever the user leaves its route, you can add a route listener in your single-spa root config:
import { registerApplication, start, unmountApplication } from 'single-spa'; // Register your apps as usual registerApplication( 'app-a', () => import('./src/app-a/main.js'), location => location.pathname.startsWith('/app-a') ); registerApplication( 'app-b', () => import('./src/app-b/main.js'), location => location.pathname.startsWith('/app-b') ); // Listen for route changes and unmount app A when we leave its path window.addEventListener('popstate', () => { const currentPath = window.location.pathname; if (!currentPath.startsWith('/app-a')) { unmountApplication('app-a').catch(err => console.error('卸载失败:', err)); } }); start();
Important Cleanup Tip
Make sure your app A’s unmount lifecycle hook handles cleanup properly to avoid memory leaks. For a React app, this means unmounting the React root and clearing any timers, subscriptions, or event listeners:
// In app-a's main.js import ReactDOM from 'react-dom'; export function unmount(props) { // Unmount the React root from its DOM node return ReactDOM.unmountComponentAtNode(document.getElementById('app-a-root')); }
内容的提问来源于stack exchange,提问作者Lawrence Moraira

