如何使用电子反应路由器?

问题描述 投票:28回答:6

使用this boilerplate作为参考我创建了一个Electron应用程序。它使用webpack捆绑脚本并表达服务器来托管它。

Webpack配置与this和服务器this几乎相同。

Electron的脚本加载:

mainWindow.loadURL('file://' + __dirname + '/app/index.html');

index.html加载服务器托管的脚本:

<script src="http://localhost:3000/dist/bundle.js"></script>

我运行electron index.js来构建应用程序和node server启动服务器,使用webpack捆绑脚本。

它工作正常,我的React组件App已安装。但是我如何将react-router集成到这个中呢?

我以与在浏览器应用程序中相同的方式实现它。我收到此错误:

[react-router] Location "/Users/arjun/Documents/Github/electron-app/app/index.html" did not match any routes

它将文件路径作为路径。通过锅炉板代码没有帮助。我错过了什么?

javascript reactjs react-router electron
6个回答
20
投票

另一种选择是使用hashHistory。实际上,在您引用的repo you can see that they're using hashHistory中,如何尝试并回发?


23
投票

我正在使用React Router v4并且不想回退到HashRouter,所以我用以下的东西解决了它:

import { Redirect, BrowserRouter } from 'react-router-dom';

const App = () => (
  <BrowserRouter>
    <div>
      {window.location.pathname.includes('index.html') && <Redirect to="/" />}
    </div>
  </BrowserRouter>
);

21
投票

Had to Replace BrowserRouter with HashRouter.

import {
  HashRouter,
  Route
} from "react-router-dom";

然后在我的index.js或Electron应用程序的条目文件中我有这样的事情:

<HashRouter>
  <div>
    <Route path="/" exact     component={ Home } />
    <Route path="/firstPage"  component={ FirstPage } />
    <Route path="/secondPage" component={ SecondPage } />
  </div>
</HashRouter>

然后一切正常。

原因是:BrowserRouter适用于基于请求的环境,而HashRouter适用于基于文件的环境。

在这里阅读更多:


10
投票

this答案的最佳选择是使用MemoryRouter,为我工作:)


2
投票

(当前)react-router docs say

一般来说,如果您有响应请求的服务器,则应使用<BrowserRouter>,如果使用静态文件服务器,则应使用<HashRouter>。

Electron应用程序基本上是一个静态文件服务器。

MemoryRouter也可以工作,只要所有路由都源自应用程序的React部分。只有当您想要从浏览器流程导航到特定页面时,它才会失效,例如您想要弹出一个新窗口并直接导航到“常规首选项”页面。在这种情况下,您可以使用HashRouter执行此操作:

prefsWindow.loadURL(`file://${__dirname}/app/index.html#/general-prefs`);

我不认为有一种方法可以使用MemoryRouter(来自浏览器进程)。


2
投票

同意Niekert。但我相信在任何路由管理之前最好这样处理。

if ( window.location.pathname.includes('index.html') ) {
    location.pathname = ROUTES.ROOT;
}
© www.soinside.com 2019 - 2024. All rights reserved.