使用React Router DOM开发CRA时路由跳转外部JS未加载问题咨询
Hey, I’ve run into this exact issue before with React Router and external scripts in Create React App—here’s what worked for me:
Why This Happens
React Router powers single-page applications (SPAs), which means when you navigate between routes, the browser doesn’t reload the entire index.html file. The external scripts you added to index.html only load and run once during the app’s initial page load. When you switch routes later, those scripts don’t re-execute, which causes the issue you’re seeing.
Solutions
1. Dynamically Load the Script in Specific Components
If the external JS is only needed in certain components, use the useEffect hook to inject the script when the component mounts, and clean it up when it unmounts.
Example code:
import { useEffect } from 'react'; function CheckoutPage() { useEffect(() => { // Create a script element const externalScript = document.createElement('script'); externalScript.src = 'https://your-external-script-url.js'; externalScript.async = true; // Append to the document body document.body.appendChild(externalScript); // Cleanup: remove the script when component unmounts return () => { document.body.removeChild(externalScript); // If the script has a cleanup function, call it here if (window.cleanupExternalScript) { window.cleanupExternalScript(); } }; }, []); // Empty dependency array = runs once on mount return ( <div> <h1>Checkout Page</h1> {/* Your component content here */} </div> ); } export default CheckoutPage;
If the script needs to run an initialization function once loaded, add an onload handler:
externalScript.onload = () => { // Call the script's global init function window.initExternalService(); };
2. Load the Script Globally on App Initialization
If the external JS is required across your entire app, load it before rendering your React app in src/index.js. This ensures it’s available from the start, even when navigating between routes.
Example code:
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; function loadGlobalScript() { const script = document.createElement('script'); script.src = 'https://your-external-script-url.js'; script.async = true; // Render the app only after the script loads script.onload = () => { const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <App /> </React.StrictMode> ); }; document.body.appendChild(script); } // Trigger the script load loadGlobalScript();
3. Avoid Inline Scripts in index.html (Alternative)
Instead of adding scripts directly to index.html, consider installing the library via npm if it’s available. For example:
npm install your-external-library
Then import it directly into your components or index.js:
import 'your-external-library';
This is the most "React-native" approach and avoids SPA navigation issues entirely.
内容的提问来源于stack exchange,提问作者Alex Rodriguez

