生产过程中如何在Electron React App中路由

CVK*_*VKM 8 javascript reactjs electron electron-builder

我正在使用 Electron 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>
Run Code Online (Sandbox Code Playgroud)

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

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

提前致谢。

小智 5

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

\n\n

hash向 url 格式添加了属性,一切正常。

\n\n
const path = require('path')\nconst url = require('url')\n\nurl.format({\n    pathname: path.join(__dirname, 'index.html'),\n    hash: '/add',\n    protocol: 'file:',\n    slashes: true\n})\n
Run Code Online (Sandbox Code Playgroud)\n


CVK*_*VKM 4

好的,我通过在链接末尾添加 #/add 解决了这个问题,如下所示:

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

Run Code Online (Sandbox Code Playgroud)

  • 这对电子不起作用。“#”符号将被转换为“%23”,这会破坏路由。最好使用 ```const path = require('path') const url = require('url') url.format({ pathname: path.join(__dirname, 'index.html'), hash: '/add ',协议:'文件:',斜杠:true}) ``` (3认同)