如何在生产过程中在电子反应应用程序中路由



我正在使用电子6.10.0并使用React.js。

在我的应用程序中,菜单中有一个添加任务选项,用于创建一个新窗口。

在开发过程中一切正常,但在生产过程中,这条生产线会导致问题。

addWindow.loadURL(isDev ? 'http://localhost:3000/add' : `file://${path.join(__dirname, '../build/index.html')}`);

它加载索引.html,通过它加载索引.js并呈现路由器.js。这是路由器.js中的代码。

<HashRouter>
<Switch>
<Route exact path="/" component={App} />
<Route exact path="/add" component={addWindow} />
</Switch>
</HashRouter>

主窗口工作正常,因为哈希是 '/',但对于添加窗口,哈希不会更改,它会在 addwindow 中再次加载主窗口内容。

如何在生产过程中使用路由/路由器,或者是否有其他方法。

提前谢谢。

就我而言,我在编码为/build/index.html%23add的路径中的哈希片段出现问题,并且该文件/url 不存在。

我将hash属性添加到 url 格式,一切正常。

const path = require('path')
const url = require('url')
url.format({
pathname: path.join(__dirname, 'index.html'),
hash: '/add',
protocol: 'file:',
slashes: true
})

好的,我通过在链接末尾添加 #/add 来解决它,如下所示:

addWindow.loadURL(isDev ? 
'http://localhost:3000/add' :
`file://${path.join(__dirname, '../build/index.html#/add')}`);

我在尝试构建 electron/react 应用程序时遇到了同样的问题。 url.format(( 就像一个魅力,但不幸的是,自节点 v11 以来它已被弃用。我做了一个简单的帮助程序函数,它使用新的 URL 类语法。

const isDev = require('electron-is-dev');
const { URL } = require('url');
// Define React App dev and prod base paths
const devBasePath = 'http://localhost:3000/';
const prodBasePath = `file://${__dirname}/build/index.html`;
const constructAppPath = (hashRoute = '') => {
const basePath = isDev ? devBasePath : prodBasePath;
const appPath = new URL(basePath);
// Add hash route to base url if provided
if (hashRoute) appPath.hash = hashRoute;
// Return the constructed url
return appPath.href;
};
console.log('initial path', constructAppPath());
console.log('hash path', constructAppPath('/example/path'));

最新更新