Create-React-App站点Netlify部署后React Router功能异常求助
Hey there! I’ve run into this exact React Router problem dozens of times when deploying single-page apps (SPAs) to Netlify—let’s get it sorted out quickly.
Why This Happens
When you directly visit a route like /about or refresh the page, Netlify tries to look for a physical file at that path (like /about.html), but your React app only has one entry point: index.html. Since that file doesn’t exist, you get an error. React Router handles routing client-side, so we need to tell Netlify to send all traffic to index.html first.
The Fix: Add a Redirect Rule
There are two easy ways to set this up—pick whichever you prefer:
Option 1: Use a _redirects File
- In your Create-React-App project, navigate to the
publicfolder. - Create a new file named
_redirects(no file extension). - Paste this line into the file:
/* /index.html 200 - Commit this file to your Git repository and redeploy to Netlify. Netlify will automatically detect and apply this rule.
Option 2: Use a netlify.toml Configuration File
- At the root of your project, create a file named
netlify.toml. - Add this configuration to the file:
[[redirects]] from = "/*" to = "/index.html" status = 200 - Commit and redeploy—this achieves the same result as the
_redirectsfile.
Quick Check for Your Route Setup
Looking at your Router code, using process.env.PUBLIC_URL is smart for handling subpath deployments. Just make sure:
- If your site is deployed at Netlify’s root (e.g.,
your-site.netlify.app),PUBLIC_URLwill be empty, so your routes work as-is. - If you’re deploying to a subpath (e.g.,
your-site.netlify.app/my-app), set thehomepagefield in yourpackage.jsonto match that subpath (like"homepage": "/my-app").
Once you add the redirect rule and redeploy, refreshing pages or directly accessing routes should work perfectly—React Router will take over and render the correct component every time.
内容的提问来源于stack exchange,提问作者danH

