2016-04-08 34 views
16

使用this boilerplate作为参考我创建了一个Electron应用程序。它使用webpack捆绑脚本,并使用express服务器来托管它。如何使用带电子的React路由器?

Webpack配置实际上与this和服务器this相同。

电子的脚本加载:

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组件应用程序被挂载。但是,我如何将反应路由器集成到此?

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

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

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

+0

获取完全相同的东西。你有没有找到一个解决方案,@ arjun-u - 或者你只是去hashHistory而不是? –

+1

我使用了hashHistory。 –

回答

14

另一种选择是使用hashHistory代替。其实,在你参考的回购you can see that they're using hashHistory,如何尝试和回发?

+0

HashRouter已被弃用,所以我和Niekert的答案一起去了。 https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/HashRouter.md – user1132959

11

我使用的阵营路由器v4和不想回退到HashRouter,所以我的东西的喜欢当中解决了这个问题:

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

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

你的解决方案的工作除了重新加载电子将导致一个空白页面。这在“生产”中不是问题,但在开发中我经常需要重新加载。它发生在你身上吗? – Amida

0

(当前)react-router docs say

Generally speaking, you should use a <BrowserRouter> if you have a server that responds to requests and a <HashRouter> if you are using a static file server.

电子应用是浅特别是一个静态文件服务器。

MemoryRouter也可以工作,只要所有路由源自应用的React部分。只有当你想浏览浏览器进程中的特定页面时,它才会下降,例如你想弹出一个新窗口并直接导航到“常规首选项”页面。在这种情况下,你可以用HashRouter做到这一点:

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

我不认为有一种方法可以做到这一点与MemoryRouter(从浏览器进程)。