简体   繁体   English

React-router-dom + Suspense:gh-pages 部署中的问题

[英]React-router-dom + Suspense : Problem in gh-pages deployment

I am working on a React app which uses react-router-dom for routing alongside React.lazy() and Suspense for code-splitting.我正在开发一个 React 应用程序,它使用react-router-dom进行路由以及React.lazy()Suspense进行代码拆分。

It is the same gh-pages giving 404 error problem everyone had and when I encountered it before this, adding the basename prop to the BrowserRouter component would work.这是相同的 gh-pages 给出每个人都遇到过的 404 错误问题,当我在此之前遇到它时,将 basename prop 添加到 BrowserRouter 组件就可以了。 However, even after adding the basename prop , if I go to a certain route and refresh, the 404 page appears.但是,即使在添加了 basename属性之后,如果我将 go 转到某个路由并刷新,也会出现 404 页面。 Also if I directly access a route through the Browser, the 404 appears again.此外,如果我直接通过浏览器访问路由,404 将再次出现。

My current workaround is to use HashRouter instead of BrowserRouter which doesn't let the app break in production.当前的解决方法是使用HashRouter而不是 BrowserRouter,这不会让应用程序在生产中中断。 However, it puts hashes into the routes.但是,它将哈希放入路由中。 Has anyone made the BrowserRouter work with Suspense in deployment on gh-pages or on any other deployment service?有没有人让 BrowserRouter 在 gh-pages 或任何其他部署服务上的部署中与 Suspense 一起工作? A suggestion for a better deployment option for the app is welcome.欢迎为应用程序提供更好的部署选项的建议。

Here are my routes in code and an example illustrating the issue:这是我的代码路线和说明问题的示例:

 import React, {Suspense} from "react"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Fallback from "./components/Fallback" const Carousel = React.lazy(()=>import("./components/carousel/Carousel")) const Home = React.lazy(()=>import("./components/Home")) function App() { return ( <div className="App"> <Router basename="/home"> <Suspense fallback={Fallback()}> <Switch> <Route exact path="/" component={Home} /> <Route path="/carousel" component={Carousel} /> </Switch> </Suspense> </Router> </div> ); }

Here, if I go to the deployed site, (say URL: .github.io/home) I see the home page at /.在这里,如果我 go 到已部署的站点,(例如 URL:.github.io/home),我会在 / 看到主页。 Now if a link takes me to the /carousel route, I can see the carousel page but if I refresh, there are the 404 pages.现在,如果链接将我带到 /carousel 路线,我可以看到轮播页面,但如果我刷新,则会出现 404 页面。 Also if I directly access /carousel, the 404 pages again.另外如果我直接访问/carousel,404页面又来了。 I would love a workaround other than HashRouter which I'm already using.除了我已经在使用的 HashRouter 之外,我会喜欢一种解决方法。

I don't suggest deploying SPAs to gh-pages.我不建议将 SPA 部署到 gh-pages。

If you want a better service I would suggest using Netlify.如果您想要更好的服务,我建议您使用 Netlify。

Go ahead and deploy your app it is really easy, I am sure that your problem will disappear.提前 Go 部署您的应用程序真的很容易,我相信您的问题会消失。

www.netlify.com www.netlify.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM