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

IT技术 javascript reactjs electron electron-builder
2021-05-25 02:02:44

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

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

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

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

它加载 index.html,通过它加载 index.js 并呈现 router.js。这是 Router.js 中的代码。

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

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

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

提前致谢。

3个回答

就我而言,我遇到了编码为 的路径中的哈希片段问题/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')}`);

我在尝试构建电子/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'));