晚上好,我的问题与反应路由器有关。
这是我的 App.js,我的所有路线都在处理中
const App = () => (
<div className="App">
<MediaQuery minWidth={700}>
{(matches) => {
if (matches) {
return (<Router>
<div>
<Headroom>
<Header />
</Headroom>
<main>
<Route exact path='/' component={homepage} />
<Route path='/home' component={homepage} />
<Route path='/OurPubs' component={OurPubs} />
<Route path='/OurEmail' component={OurEmail} />
<Route path='/OurQuest' component={OurQuest} />
<Route path='/StayRelevant' component={StayRelevant} />
<Route path='/GetCurious' component={GetCurious} />
<Route path='/TheGoods' component={TheGoods} />
<Route path='/post/:slug' component={Post}>
<Redirect from="*" to="/" />
</Route>
</main>
</div>
</Router>
因为我使用 GraphQL 来获取数据并使用模板(其中每个 Post 在某种意义上代表一个 Route)
因为**<Route path='1' component=>**将用户带到不同的帖子。
现在,如果在移动设备上,删除缓存后,浏览器将显示 ERROR 404 消息。哪个是正确的,毕竟 url post/XXXX 实际上并不存在于服务器上。
Not Found
The requested URL /post/XXXX was not found on this server.
只有在浏览器退出后在帖子内或移动设备上刷新时才会出现此问题。
问题是我如何简单地将用户从未知路线带回 path =“/”(家)?
3 回答
当从服务器调用以获取
slug
在Post
组件中解析的帖子时,您需要检查它是否为 404,如果是,则您将导航用户到主页。如果你给我更多关于
Post
组件的信息,或者那个电话的地方,我可以给你自信的解决方案,但基本的想法就像上面一样。TL; DR:配置 HTTP 服务器以将所有请求重定向到/index.html
这里的问题似乎是你的HTTP 服务器返回 404.这意味着当你访问/index.html(React 代码所在的位置)时,应用程序被加载,当用户与应用程序交互时,URL 会发生变化没有用 react-router 重新加载页面。
刷新时,您要求 HTTP 服务器提供不是您的 React 应用程序的文件。因此,您应该配置 HTTP 服务器以将所有请求(如/post/XXXX)重定向到/index.html。
这个问题可能有所帮助:https://serverfault.com/questions/188373/apache-2-2-rewrite-force-all-requests-to-index-html
快速方式之一,您可以在 api 客户端设置一个拦截器,如 fetch api,superagent 等,如下所示: