reactjs - 未找到生产抛出文件中的哈希路由错误
问题描述
我正在使用 electron-react-boilerplate 并想在新的 BrowserWindow 中打开一个组件。关于如何执行此操作有多个问题和答案,但在打包应用程序后它们都不起作用。
我发现的问题/答案:
在我的组件中,我尝试使用以下几行打开一个新窗口到不同的路线。
wind.loadURL(`file://${__dirname}/app.html#/video`)
wind.loadURL(`file://${Path.join(__dirname, '../build/app.html#/video')}`)
wind.loadURL(`file://${Path.join(__dirname, '../build/index.html#/video')}`)
第一个在运行 yarn dev 时有效,但在生产中无效。他们都为各自的路径抛出 ERR_FILE_NOT_FOUND 。
这就是我的路线设置方式:
export default function Routes() {
return (
<App>
<HashRouter>
<Route exact path={routes.HOME} component={HomePage} />
<Route path={routes.VIDEO} component={VideoPage} />
</HashRouter>
</App>
);
}
使用 React 的路由器打开新的 BrowserWindow 时,是否有一种简单的方法来允许路由?
解决方案
时机很好。过去几天我在同一条船上,只是想通了。除了,我没有HashRouter
像你那样改变。相反,我将所有路由内容保留为默认值electron-react-boilerplate
,例如ConnectedRouter
. 也许任何一种方式都有效。
__dirname
仅适用于开发。我使用 DebugTron 检查为每个资源加载了哪些 URL,它是file://path/to/app.asar/something
. 然后我想出了如何到达asar的路径。无论应用程序位于何处,这对我在开发和生产中都有效。您还需要设置nodeIntegration: true
. 在 macOS 上测试。
const electron = require("electron")
//...
win.loadURL(`file://${electron.remote.app.getAppPath()}/app.html#/yourroutename`)
如果有人还想知道如何加载另一个页面并将参数传递给它,则更完整的示例:
import routes from '../constants/routes.json'
const electron = require("electron")
// ...
var win = new BrowserWindow({
width: 400, height: 400,
webPreferences: { nodeIntegration: true }
})
win.loadURL(`file://${electron.remote.app.getAppPath()}/app.html#${routes["ROOM"]}?invitationCode=${encodeURIComponent(code)}`)
win.show()
在组件中,路由加载:
const queryString = require('query-string')
// ...
constructor(props) {
super(props)
const params = queryString.parse(location.hash.split("?")[1])
this.invitationCode = params.invitationCode
}
推荐阅读
- scala - 第一个最终的无标签方法
- wpf - 在 WPF (.xaml) 中将元素的大小绑定到另一个元素并将可变长度添加到绑定大小
- angular - 创建了自定义单选按钮库,但在与反应形式绑定时未检查单选按钮
- html - XSLT:获取动态创建的属性的值
- ajax - Twbs 分页无法在数据表中加载新的页面数据
- java - 当我不关心排序时,对对象的 ArrayList 进行排序的最简单方法是什么?
- postgresql - 如何从 2 个不同的服务器将非重复值插入 PostgreSQL
- unity3d - 从设备上的统一项目中删除临时文件
- python - Mongoengine Dynamic Document, How to add item dynamically to referencefield?
- c++ - How to convert/cut uint256_t to uint8_t[ ]