【问题标题】:How to route in electron react app during production如何在生产期间在电子反应应用程序中路由
【发布时间】:2020-01-25 07:32:51
【问题描述】:

我正在使用电子 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>

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

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

提前致谢。

【问题讨论】:

    标签: javascript reactjs electron electron-builder


    【解决方案1】:

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

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

    【讨论】:

    • 尝试在开发中添加#,并在生产中从url中排除/。更新代码:addWindow.loadURL( isDev ? 'http://localhost:3000#/add' : `file://${path.join(__dirname, '../build/index.html#add')}`);
    【解决方案2】:

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

    我在 url 格式中添加了 hash 属性,一切正常。

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

    【讨论】:

      【解决方案3】:

      我在尝试构建电子/反应应用程序时遇到了同样的问题。 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'));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-01
        • 2021-01-22
        • 2020-11-06
        • 2021-01-06
        • 2019-08-02
        • 2020-02-01
        • 2021-07-19
        • 2022-08-03
        相关资源
        最近更新 更多